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

示例

给定供应商提供的类,例如:

public class VendorObject {

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

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

}

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

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

}

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.

        }
    }
);

围绕供应商类添加包装以简化模拟不是一种选择,因为:
  • 现有代码库太大。
  • 对性能至关重要的应用程序的一部分。
  • 最佳答案

    我认为您想要的是:

    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.
    
        }
    });
    

    当然,如果您想频繁使用此方法,则无需匿名回答。

    来自documentation:“这是一个相当高级的功能,通常您不需要它来编写不错的测试。但是,在使用旧系统时,它会有所帮助。”听起来像你。

    10-07 19:33
    查看更多