我正试图注入一个mock,供我正在测试的服务类使用,但该mock似乎没有被使用。
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
}
}
它抛出一个
通缉但未调用
在验证方法中
我不确定如何将mock注入到autowired实例中。有人能指出我在这里做错了什么吗?
试试这个[如果它不起作用,我会删除答案-不能把它放在评论中]
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);
}
}
在插入之前
TestUtils.setMockToProxy(service, "repository", repository);
问题是我试图将mock注入接口变量,而该接口没有任何引用变量。
我用一个具体实现引用替换了它,该引用具有用于注入模拟的引用变量,并且它在中运行良好
@InjectMocks
private Service service=new Service();