使用Mockito模拟另一个类中的类方法

Cha*_*Liu 11 java junit unit-testing mocking mockito

我正在尝试使用Mockito/JUnit为这样的函数编写单元测试:

class1 {
 method {
  object1 = class2.method // method that I want to fake the return value
  // some code that I still want to run
 }
}
Run Code Online (Sandbox Code Playgroud)

在Mockito中是否有任何方法来存根class2.method的结果?我正在尝试改进class1的代码覆盖率,所以我需要调用它真正的生产方法.

我在其间谍方法中查看了Mockito API,但这会覆盖整个方法而不是我想要的部分.

小智 6

我想我理解你的问题.让我重新说一下,你有一个函数,你试图测试并想要模拟在该函数内调用的函数的结果,但是在另一个类中.我已经按照以下方式处理了这个问题.

public MyUnitTest {
    private static final MyClass2 class2 = mock(MyClass2.class);

    @Begin
    public void setupTests() {
        when(class2.get(1000)).thenReturn(new User(1000, "John"));
        when(class2.validateObject(anyObj()).thenReturn(true);
    }

    @Test
    public void testFunctionCall() {
        String out = myClass.functionCall();
        assertThat(out).isEqualTo("Output");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是在用@Before注释包装的函数中,我正在设置我希望class2中的函数如何响应给定的特定输入.然后,从实际测试中,我只是调用我想要在我要测试的类中测试的函数.在这种情况下,myClass.functionCall()正常运行并且您不会覆盖其任何方法,但您只是模拟它从MyClass2中的方法(或方法)获得的输出.

  • 这个答案是不完整的,实际上导致某人犯了错误(http://stackoverflow.com/questions/37762496/junit-mockito-mock-one-method-in-another-class-error).我看到几个问题:1)变量/成员`myClass`永远不会被声明或初始化,并且class2永远不会传递给它.2)注释类`@ Begin`不存在 - 它应该是`@ Before`或者`@ BeforeClass` 3)成员class2应该不是静态的 - 特别是如果使用`@ Before`.应该为每个测试重新创建它.4)如果所有测试都不需要,最好在测试中存根class2. (10认同)