2016-04-04 147 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告訴我。 –