EasyMock 3.0,模拟类抛出java.lang.IllegalStateException:没有对模拟的最后一次调用 [英] EasyMock 3.0, mocking class throws java.lang.IllegalStateException: no last call on a mock available
问题描述
运行以下单元测试会引发异常:java.lang.IllegalStateException:没有对模拟的最后一次调用
Running the following unit test throws the exception: java.lang.IllegalStateException: no last call on a mock available
import org.easymock.*;
import org.junit.*;
public class MyTest {
@Test
public void testWithClass() {
Thread threadMock = EasyMock.createMock(Thread.class);
EasyMock.expect(threadMock.isAlive()).andReturn(true);
}
}
我不确定自己在做什么,可以在网络上找不到任何好的例子。您如何使用EasyMock 3.0模拟类。上面的单元测试有什么问题?任何帮助将不胜感激。
I am not sure what I am doing wrong and can not find any good examples on the web. How do you mock a class using EasyMock 3.0. What is wrong with the above unit test? Any help would be greatly appreciated.
我的项目包括以下maven依赖项
My project includes the following maven dependencies
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
推荐答案
此异常的原因是 Thread#isAlive()
是 final
方法,但是EasyMock不支持模拟最终方法。因此,对出现在 EasyMock.expect(...)
中的此方法的调用不视为模拟调用。
The reason for this exception is that Thread#isAlive()
is a final
method, but EasyMock does not support the mocking of final methods. So, the call to this method which appears inside EasyMock.expect(...)
is not seen as a "call on a mock".
要模拟最终方法,您需要使用其他模拟工具,例如JMockit(由我开发):
To mock final methods you would need a different mocking tool, such as JMockit (which I develop):
public void testMockingFinalMethod(@Mocked("isAlive") Thread mock)
{
new Expectations()
{{
mock.isAlive(); result = true;
}};
assertTrue(mock.isAlive());
}
模拟API实际上并不要求明确指定要模拟的方法,一般情况下。但是, Thread
类是一个棘手的类。
The mocking API doesn't actually require that methods to be mocked are specified explicitly, in the general case. The Thread
class is a tricky one, though.
这篇关于EasyMock 3.0,模拟类抛出java.lang.IllegalStateException:没有对模拟的最后一次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!