我正在尝试注入一个我正在测试的服务类使用的模拟但是似乎没有使用模拟。
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 :(得分: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);
答案 1 :(得分:0)
问题是我试图将模拟注入接口变量,并且接口没有任何引用变量。
我将其替换为具体实现引用,该引用具有注入模拟的引用变量,并且运行良好
@InjectMocks
private Service service=new Service();