java 用 Mockito 模拟“内部”对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15759448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mock "inner" object with Mockito
提问by RRZ Europe
Quite new to unittesting and mockito, I have a method to test which calls a method on a new object. how can I mock the inner object?
对单元测试和模拟非常新,我有一个方法来测试它在新对象上调用方法。我如何模拟内部对象?
methodToTest(input){
...
OtherObject oo = new OtherObject();
...
myresult = dosomething_with_input;
...
return myresult + oo.methodX();
}
can I mock oo to return "abc"? I really do only want to test my code, but when I mock "methodToTest" to return "42abc", then I will not test my "dosomething_with_input"-code ...
我可以模拟 oo 返回“abc”吗?我真的只想测试我的代码,但是当我模拟“methodToTest”返回“42abc”时,我不会测试我的“dosomething_with_input”代码......
回答by rcomblen
I consider the class that implements methodToTest
is named ClassToTest
我认为实现的类methodToTest
被命名ClassToTest
- Create a factory class for
OtherObject
- Have the factory as a field of
ClassToTest
- either
- pass the factory as parameter of the constructor of
ClassToTest
- or initialize it when allocating the
ClassToTest
object and create a setter for the factory
- pass the factory as parameter of the constructor of
- 创建一个工厂类
OtherObject
- 有工厂作为一个领域
ClassToTest
- 任何一个
- 将工厂作为构造函数的参数传递
ClassToTest
- 或者在分配
ClassToTest
对象时初始化它并为工厂创建一个setter
- 将工厂作为构造函数的参数传递
your test class should look like
你的测试类应该看起来像
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
// ...
}
}