我正在尝试
mockito.verify()
功能。该方法调用仅发生一次,但验证显示 3 次调用。单元测试只有一个测试,以确保该测试不会受到其他影响。
Mockito.verify(utilClass, Mockito.times(1)).hello(); /// but invocation is 3 times, says the error
我一直在查看日志,它也显示调用仅发生一次。多次添加故意调用方法
utilClass.hello()
,然后显示正确的调用次数。但在给定的代码中,它被调用一次,它出现为被调用 3 次。
待测班级:
@Component
public class UtilClass {
private static final Logger logger = LoggerFactory.getLogger(UtilClass.class);
public String hello() {
logger.info("hello method invoked");
return "Hello World,"+ hi();
}
private String hi() {
logger.info("hi method invoked");
return "Hi All";
}
}
@Component
public class ClassWithDependency {
@Autowired
private UtilClass utilClass;
public String welcome() {
String msg = utilClass.hello();
return msg;
}
}
测试用例
@InjectMocks
private ClassWithDependency classWithDependency;
@Mock
private UtilClass utilClass;
@Before
public void init() throws Exception {
PowerMockito.when(utilClass,"hi").thenReturn("Hi Java");
PowerMockito.when(utilClass.hello()).thenCallRealMethod();
}
@Test
public void testMock() throws Exception {
final String msg = classWithDependency.welcome();
final String msgExpected = "Hello World,Hi Java";
logger.info("welcome method called:{}",msg);
PowerMockito.verifyPrivate(utilClass, Mockito.times(1)).invoke("hi");
Mockito.verify(utilClass, Mockito.times(1)).hello();
Assert.assertTrue(msg.equals(msgExpected));
}
我期待mockito.verify 成功,但收到此错误:
org.mockito.exceptions.verification.TooManyActualInvocations:
utilClass.hello();
Wanted 1 time:
-> at com.sd.demo.powermock.test.injectmock.InjectMockTest.testMock(InjectMockTest.java:54)
But was 3 times:
-> at com.sd.demo.powermock.injectmock.ClassWithDependency.welcome(ClassWithDependency.java:13)
-> at com.sd.demo.powermock.injectmock.ClassWithDependency.welcome(ClassWithDependency.java:13)
-> at com.sd.demo.powermock.injectmock.ClassWithDependency.welcome(ClassWithDependency.java:13)
at com.sd.demo.powermock.test.injectmock.InjectMockTest.testMock(InjectMockTest.java:54)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:68)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:89)
.............
最后让测试工作,解决方案是'SPY'..监视util类,这样就不会告诉真正调用哪个方法。我不知道如何注入间谍,所以使用了 setter..
@InjectMocks 私有 ClassWithDependency classWithDependency;
private UtilClass mockUtil;
@Before
public void init() throws Exception {
UtilClass utilClass = new UtilClass();
mockUtil = PowerMockito.spy(utilClass);
classWithDependency.setUtilClass(mockUtil);
}
@Test
public void testMock() throws Exception {
PowerMockito.when(mockUtil,"hi").thenReturn("Hi Java");
final String msg = classWithDependency.welcome();
final String msgExpected = "Hello World,Hi Java";
logger.info("welcome method called:{}",msg);
PowerMockito.verifyPrivate(mockUtil, Mockito.times(1)).invoke("hi");
Mockito.verify(mockUtil, Mockito.times(1)).hello();
Assert.assertTrue(msg.equals(msgExpected));
}