我有一个名为MyClass
的Java类,我想用JUnit测试它。我要测试的公共方法methodA
调用同一类中的私有方法methodB
来确定要遵循哪个条件路径。我的目标是为methodA
中的不同路径编写JUnit测试。此外,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");
}
}
谢谢!