正在测试的同一类中的模拟私有方法
2022-09-02 22:36:21
我有一个名为 的 Java 类,我想用 JUnit 进行测试。我要测试的 public 方法 () 在同一类中调用私有方法 ,以确定要遵循的条件路径。我的目标是为 中的不同路径编写 JUnit 测试。另外,调用一个服务,所以我不希望它在运行JUnit测试时实际执行。MyClass
methodA
methodB
methodA
methodB
模拟和控制其返回的最佳方法是什么,以便我可以测试“方法A”的不同路径?methodB
我更喜欢在编写模拟时使用JMockit,所以我对任何适用于JMockit的答案都特别感兴趣。
这是我的示例类:
public class MyClass {
public String methodA(CustomObject object1, CustomObject object2) {
if(methodB(object1, object2)) {
// Do something.
return "Result";
}
// Do something different.
return "Different Result";
}
private boolean methodB(CustomObject custObject1, CustomObject custObject2) {
/* For the sake of this example, assume the CustomObject.getSomething()
* method makes a service call and therefore is placed in this separate
* method so that later an integration test can be written.
*/
Something thing1 = cobject1.getSomething();
Something thing2 = cobject2.getSomething();
if(thing1 == thing2) {
return true;
}
return false;
}
}
这是我到目前为止所拥有的:
public class MyClassTest {
MyClass myClass = new MyClass();
@Test
public void test_MyClass_methodA_enters_if_condition() {
CustomObject object1 = new CustomObject("input1");
CustomObject object2 = new CustomObject("input2");
// How do I mock out methodB here to return true?
assertEquals(myClass.methodA(object1, object2), "Result");
}
@Test
public void test_MyClass_methodA_skips_if_condition() {
CustomObject object1 = new CustomObject("input1");
CustomObject object2 = new CustomObject("input2");
// How do I mock out methodB here to return false?
assertEquals(myClass.methodA(object1, object2), "Different Result");
}
}
谢谢!