我有一个名为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");
}
}
谢谢!
对于这种情况,使该方法包私人即“默认”访问符。我使用EasyMock#createMockBuilder()创建部分模拟,所以我可以模拟该私有方法。不知道你的JMockit的等价物。 – deepakraut
您对Easymock - Powermock解决方案感兴趣吗?否则,我想写出来给你。 –
参见http://stackoverflow.com/questions/250692/how-do-you-unit-test-private-methods – Raedwald