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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:46:16  来源:igfitidea点击:

Mock "inner" object with Mockito

javajunitmockito

提问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 methodToTestis 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 ClassToTestobject and create a setter for the factory
  • 创建一个工厂类 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
        // ...
    }
}