2016-04-04 61 views
1

我想注入一个模拟被我正在测试的服务类使用,但模拟似乎没有被使用。弹簧注入模拟不使用

public class SpringDataJPARepo{ public void someMethod();// my repo } 

我有希望测试

@Service 
    public class Service implements IService{ 

    @Autowired 
    private SpringDataJPARepo repository; 

    public String someMethod(){ // repository instance used here } 
    } 

服务类,我试图通过嘲笑库,并将其注入到服务

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes={ServiceTestConfiguration.class}) 
public class Test{ 

@Mock 
private SpringDataJPARepo repository; 

@Autowired 
@InjectMocks 
private IService service; 

@Before 
public void setup(){ 
MockitoAnnotations.initMocks(this); 
when(repository.someMethod()).thenReturn("test"); 
} 

@Test 
public testSomeMethod(){ 
assertThat(service.someMethod()).isNotNull; 
verify(repository.someMethod,atLeast(1)); //fails here 
} 

} 

它给我写测试用例抛出一个

通缉但未被调用

的验证方法

我不知道在如何注入模拟到自动装配实例。任何人都可以指出我在这里做错了什么?

+0

是您的服务或为除了“@服务”任何Spring注解的方法,如“@交易“或”@Secured“? –

+0

不,它没有任何其他注释 – austin

+0

您的服务类除了'SpringDataJPARepo'外还有其他任何依赖吗? – Bunti

回答

0

问题是我试图将模拟注入接口变量,并且该接口没有任何引用变量。
我有具体实施参考具有参考变量的注入嘲笑取代它和它运作良好

@InjectMocks 
private Service service=new Service(); 
1

试试这个[我会删除答案,如果它不工作 - 不能把这个在评论]

public class TestUtils { 

    /** 
    * Unwrap a bean if it is wrapped in an AOP proxy. 
    * 
    * @param bean 
    *   the proxy or bean. 
    *    
    * @return the bean itself if not wrapped in a proxy or the bean wrapped in the proxy. 
    */ 
    public static Object unwrapProxy(Object bean) { 
     if (AopUtils.isAopProxy(bean) && bean instanceof Advised) { 
      Advised advised = (Advised) bean; 
      try { 
       bean = advised.getTargetSource().getTarget(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     return bean; 
    } 

    /** 
    * Sets a mock in a bean wrapped in a proxy or directly in the bean if there is no proxy. 
    * 
    * @param bean 
    *   bean itself or a proxy 
    * @param mockName 
    *   name of the mock variable 
    * @param mockValue 
    *   reference to the mock 
    */ 
    public static void setMockToProxy(Object bean, String mockName, Object mockValue) { 
     ReflectionTestUtils.setField(unwrapProxy(bean), mockName, mockValue); 
    } 
} 

在@Before插入

TestUtils.setMockToProxy(service, "repository", repository); 
+0

@austin告诉我。 –