我有一个名为 的 Java 类MyClass
,我想用 JUnit 对其进行测试。methodA
我要测试的公共方法调用methodB
同一类中的私有方法 ,以确定要遵循的条件路径。我的目标是为methodA
. 另外,methodB
调用服务,所以我不希望在运行 JUnit 测试时实际执行它。
模拟和控制其返回的最佳方法是什么,methodB
以便我可以测试“methodA”的不同路径?
我更喜欢在编写模拟时使用 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");
}
}
谢谢!