单元测试和 mockito 很新,我有一个方法来测试它调用新对象上的方法。 我如何模拟内部对象?
methodToTest(input){
...
OtherObject oo = new OtherObject();
...
myresult = dosomething_with_input;
...
return myresult + oo.methodX();
}
我可以模拟 oo 返回“abc”吗? 我真的只想测试我的代码,但是当我模拟“methodToTest”返回“42abc”时,我将不会测试我的“dosomething_with_input”代码 ...
最佳答案
我认为实现 methodToTest
的类被命名为 ClassToTest
- 为
OtherObject
创建工厂类 - 将工厂作为
ClassToTest
的字段 - 要么
- 将工厂作为
ClassToTest
构造函数的参数传递 - 或者在分配
ClassToTest
对象时初始化它,并为工厂创建一个setter
- 将工厂作为
你的测试类应该是这样的
public class ClassToTestTest{
@Test
public void test(){
// Given
OtherObject mockOtherObject = mock(OtherObject.class);
when(mockOtherObject.methodX()).thenReturn("methodXResult");
OtherObjectFactory otherObjectFactory = mock(OtherObjectFactory.class);
when(otherObjectFactory.newInstance()).thenReturn(mockOtherObject);
ClassToTest classToTest = new ClassToTest(factory);
// When
classToTest.methodToTest(input);
// Then
// ...
}
}
关于java - 用 Mockito 模拟 "inner"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15759448/