使用 JMockit 模拟被测类的私有方法
2022-09-03 18:08:54
我想模拟被测类的私有方法,但是当调用该方法后,方法前两次返回false,之后它应该返回false。这是我尝试过的代码。这是正在测试的类
public class ClassToTest
{
public void methodToTest()
{
Integer integerInstance = new Integer(0);
boolean returnValue= methodToMock(integerInstance);
if(returnValue)
{
System.out.println("methodToMock returned true");
}
else
{
System.out.println("methodToMock returned true");
}
System.out.println();
}
private boolean methodToMock(int value)
{
return true;
}
}
测试类
import org.junit.Test;
import static mockit.Deencapsulation.*;
import mockit.*;
public class TestAClass
{
@Tested ClassToTest classToTestInstance;
@Test
public void test1()
{
new NonStrictExpectations(classToTestInstance)
{
{
invoke(classToTestInstance, "methodToMock", anyInt);
returns(false);
times = 2;
invoke(classToTestInstance, "methodToMock", anyInt);
returns(true);
times = 1;
}
};
classToTestInstance.methodToTest();
classToTestInstance.methodToTest();
classToTestInstance.methodToTest();
}
}
我这样做是为了得到理想的结果
final StringBuffer count = new StringBuffer("0");
new NonStrictExpectations(classToTestInstance)
{
{
invoke(classToTestInstance, "methodToMock", anyInt);
result= new Delegate()
{
boolean methodToMock(int value)
{
count.replace(0, count.length(), Integer.valueOf(Integer.valueOf(count.toString())+1).toString());
if(Integer.valueOf(count.toString())==3)
{
return true;
}
return false;
}
};
}
};