我有一个非常简单的方法,我正在尝试进行单元测试:
public class MyAntTask extends org.apache.tools.ant.Task {
public void execute() {
fire();
}
public void fire() {
// Do stuff
}
}
我只想写一个单元测试来确认调用execute()
总是调用fire()
,所以我写了这个:
@Test
public void executeCallsFire() {
//GIVEN
MyAntTask myTask = Mockito.mock(MyAntTask.class);
// Configure the mock to throw an exception if the fire() method
// is called.
Mockito.doThrow(new RuntimeException("fired")).when(myTask).fire();
// WHEN
try {
// Execute the execute() method.
myTask.execute();
// We should never get here; HOWEVER this is the fail() that's
// being executed by JUnit and causing the test to fail.
Assert.fail();
}
catch(Exception exc) {
// THEN
// The fire() method should have been called.
if(!exc.getMessage().equals("fired"))
Assert.fail();
}
}
我猜(而且我绝不是专家)Mockito 通常不能模拟返回的方法void
,但这是一种解决方法。你基本上说“用一个包装我的对象,每当一个特定的方法即将被执行时Mock
,它总是返回一个特定的”。RuntimeException
因此,fire()
Mockito 并没有实际执行,而是看到它即将执行并抛出异常。执行验证?查看。
它没有通过,而是在Assert.fail()
调用myTask.execute()
.
对于我的生活,我无法弄清楚为什么。这是 JUnit 给我的失败的巨大堆栈跟踪的前 10 行左右:
java.lang.AssertionError
at org.junit.Assert.fail(Assert.java:92)
at org.junit.Assert.fail(Assert.java:100)
at net.myproj.ant.tasks.MyAntTaskUnitTest.executeCallsFire(MyAntTaskUnitTest.java:32)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
StackOverflow 的 Mockito 大师们,这里有什么想法吗?提前致谢!