Mockito - 拦截模拟上的任何方法调用

Kar*_*rle 25 java unit-testing mockito

是否有可能以通用方式拦截模拟上的所有方法调用?

给定供应商提供的类如:

public class VendorObject {

    public int someIntMethod() {
        // ...
    }

    public String someStringMethod() {
        // ...
    }

}
Run Code Online (Sandbox Code Playgroud)

我想创建一个模拟,将所有方法调用重定向到另一个具有匹配方法签名的类:

public class RedirectedToObject {

    public int someIntMethod() {
        // Accepts re-direct
    }

}
Run Code Online (Sandbox Code Playgroud)

Mockito中的when().thenAnswer()构造似乎符合要求,但我无法找到一种方法来匹配任何方法调用与任何args.无论如何,InvocationOnMock肯定会给我所有这些细节.有没有通用的方法来做到这一点?看起来像这样的东西,其中when(vo.*)被适当的代码替换:

VendorObject vo = mock(VendorObject.class);
when(vo.anyMethod(anyArgs)).thenAnswer(
    new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) {

            // 1. Check if method exists on RedirectToObject.
            // 2a. If it does, call the method with the args and return the result.
            // 2b. If it does not, throw an exception to fail the unit test.

        }
    }
);
Run Code Online (Sandbox Code Playgroud)

在供应商类周围添加包装以使模拟变得简单不是一种选择,因为:

  1. 现有代码库太大.
  2. 部分极其性能关键的应用程序.

jhe*_*cks 39

我想你想要的是:

VendorObject vo = mock(VendorObject.class, new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) {

        // 1. Check if method exists on RedirectToObject.
        // 2a. If it does, call the method with the args and return the
        // result.
        // 2b. If it does not, throw an exception to fail the unit test.

    }
});
Run Code Online (Sandbox Code Playgroud)

当然,如果你想经常使用这种方法,那么答案就不需要匿名.

文档中可以看出:"它是非常先进的功能,通常你不需要它来编写体面的测试.但是在使用遗留系统时它会很有帮助." 听起来像你.