public interface Dummy {
public returnSomething doDummyWork(arg1, agr2);
}
public class A implements Dummy {
@AutoWired
PrintTaskExecutor printTaskExecutor;
public returnSomething doDummyWork(arg1, agr2) {
callingVoidMethod();
return something;
}
public void callingVoidMethod() {
printTaskExecutor.printSomething(arg1, arg2);
}
}
public class testDummy {
@Autowired
Dummy dummyA//this bean is configured in ApplicationContext.xml and it works fine.
@Mock
PrintTaskExecutor printaskExecutor;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
printaskExecutor = Mockito.mock(PrintTaskExecutor.class);
Mockito.doNothing().when(printaskExecutor).printSomething(anyString(), anyString());
}
@Test
Public void testA
{
Dummy.doDummyWork(arg1, arg2);//I m giving actual arguments
//instead of moocking it calls the original method.
Mockito.verify(printaskExecutor, times(1)).printSomething(anyString(), anyString());
}
}
我在测试的类中有一个自动装配的TaskExecutor,我想要模拟它。我已经在我的代码中尝试了这个并且它调用实际的方法而不是什么都不做,并且在验证它错误时说没有发生交互。我该如何处理这种情况?
答案 0 :(得分:0)
我尽量避免在一次测试中一起使用Mockito和Bean Containers。有解决方案可以解决这个问题。如果您使用Spring,则应使用@RunWith(SpringJUnit4Runner.class)
。有关此主题的更多信息:Injecting Mockito mocks into a Spring bean
干净的方式:实际上,您的班级testDummy
不会测试Dummy
而是A.所以您可以通过以下方式重写您的班级:
public class testA {
@Mock
PrintTaskExecutor printTaskExecutor;
@InjectMocks
A dummyA;
...
BTW:@Mock
与initMocks(this)
和printaskExecutor = Mockito.mock(PrintTaskExecutor.class);
一样,您可以跳过后一种说法。