【问题标题】:Mock "inner" object with Mockito用 Mockito 模拟“内部”对象
【发布时间】:2013-04-09 17:04:25
【问题描述】:

对于 unittesting 和 mockito 来说非常新,我有一个方法来测试它调用一个新对象的方法。 如何模拟内部对象?

methodToTest(input){
...
OtherObject oo = new OtherObject();
...
myresult = dosomething_with_input;
...
return myresult + oo.methodX();
}

我可以模拟 oo 以返回“abc”吗? 我真的只想测试我的代码,但是当我模拟“methodToTest”返回“42abc”时,我不会测试我的“dosomething_with_input”-code ...

【问题讨论】:

  • 您是在问code.google.com/p/mockito/wiki/MockingObjectCreation 回答的问题还是我误解了您?
  • 你是对的,这回答了我的问题,我已经预料到了。但我希望找到一种没有对象创建方法的方法,因为我不想更改代码只是为了能够对其进行单元测试......

标签: java junit mockito


【解决方案1】:

我认为实现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
        // ...
    }
}

【讨论】:

  • 这可能是最好的方法。但是,作为仅供参考,PowerMock 确实允许模拟构造函数调用。同样,我会建议上面的 PowerMock。
  • 唯一的“问题”是我必须重构测试代码以符合这种模式
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 2013-03-07
  • 2017-08-21
相关资源
最近更新 更多