我已经四处寻找这个问题并且没有找到我需要的东西。我学到了更多关于JMockit和嘲笑的知识。这很好。似乎每个人都想知道如何确保某些事情已经执行。我想学习相反的事情。
好的 - 我正在编写一个测试来检查公共方法中不那么开心的路径。正在测试的方法是void
,因此我无法assert
结果。 我想要做的是验证在此测试用例中未执行某个方法。
例如:
class ClassToTest {
private void method(String arg){}
public void publicMethod(String arg0, String arg1){
if(false){
//this method should never get called.
method(arg0);
}
}
}
class TestingClass{
@Tested
private ClassToTest classToTest = new ClassToTest();
@Test
public void testCheckingIfPrivateMethodWasCalled(){
classToTest.publicMethod("string1", "string2");
new Verifications() {
{
//At this point I am trying something like
Deencapsulation.invoke(classToTest, "method", "string1");
times = 0; //Also tried maxTimes = 0;
//Through debug it looks like the invoke is doing what it's named...
//invoking the private method, I don't want to invoke.
//How do I check that ClassToTest#method was not called?
}
}
}
}
我得到的测试用例的结果是java.lang.IllegalStateException: Missing invocation to mocked type at this point; please make sure such invocations appear only after the declaration of a suitable mock field or parameter
。这是times = 0;
。
我知道invoke
正在执行私有方法。我一直在试图弄清楚如何“检查”调用所述方法而不调用/执行它。
感谢。
答案 0 :(得分:0)
这样做的一种方法是使用faking的MockUp API:
import static org.junit.Assert.assertFalse;
import org.junit.Test;
import mockit.Mock;
import mockit.MockUp;
import mockit.Tested;
public class TestingClass {
@Tested
private ClassToTest classToTest = new ClassToTest();
@Test
public void testCheckingIfPrivateMethodWasCalled() {
PrivateMethodCheckMockUp mockUp = new PrivateMethodCheckMockUp() {
@Mock
private void method(String arg) {
calledPrivate = true;
}
};
classToTest.publicMethod("string1", "string2");
assertFalse(mockUp.calledPrivate);
}
class PrivateMethodCheckMockUp extends MockUp<ClassToTest> {
boolean calledPrivate = false;
@Mock
private void method(String arg) {
calledPrivate = true;
}
}
}