在Jmockit停止嘲笑
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Jmockit停止嘲笑相关的知识,希望对你有一定的参考价值。
我正在使用JMockit。我在嘲笑一种方法。我想在应该调用实际方法之后应该调用一次模拟方法。我正在提供我正在使用的代码。
package StopMocking;
public class ClassToMock
{
public int methodToMock()
{
return 2;
}
}
这是我正在测试的课程
package StopMocking;
public class ClassToTest
{
public void methodToTest()
{
ClassToMock classToMockInstance = new ClassToMock();
System.out.println(""+classToMockInstance.methodToMock());
}
}
这是测试类。
package StopMocking;
import org.junit.Test;
import mockit.Mocked;
import mockit.NonStrictExpectations;
public class TestAClass
{
@Mocked("methodToMock") ClassToMock classToMockMockedInstance;
@Test
public void test1()
{
new Expectations(classToMockMockedInstance)
{
{
classToMockMockedInstance.methodToMock();returns(1);
}
};
(new ClassToTest()).methodToTest();
//Some code for stoping mocking
(new ClassToTest()).methodToTest();//It should display 2
}
}
当我使用新的Expectations(classToMockMockedInstance)时,它会抛出此异常
mockit.internal.MissingInvocation: Missing invocation of:
StopMocking.ClassToMock#methodToMock()
on mock instance: StopMocking.ClassToMock@15093f1
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: Missing invocation
at StopMocking.ClassToMock.methodToMock(ClassToMock.java)
at StopMocking.TestAClass$1.<init>(TestAClass.java:21)
at StopMocking.TestAClass.test1(TestAClass.java:18)
... 6 more
答案
编写测试的一种方法是使用部分模拟和严格的期望如下:
public class TestAClass
{
@Test
public void test1()
{
final ClassToMock classToMockInstance = new ClassToMock();
new Expectations(ClassToMock.class) {{
classToMockInstance.methodToMock(); result = 1;
}};
new ClassToTest().methodToTest(); // prints "1"
// This time the real method implementation will be executed:
new ClassToTest().methodToTest(); // prints "2"
}
}
以上是关于在Jmockit停止嘲笑的主要内容,如果未能解决你的问题,请参考以下文章