模拟基于反射的调用

Bal*_*ala 12 java mocking mockito ejb-3.0

我试图模拟一些基于反射的方法.在下面你可以看到细节,

被测试的班级

public class TracerLog {
    @AroundInvoke
    public Object logCall(InvocationContext context) throws Exception {
        Logger logger = new Logger();
        String message = "INFO: Invoking method - " 
                + context.getMethod().getName() + "() of Class - " 
                + context.getMethod().getDeclaringClass();

        logger.write(message);
        return context.proceed();
    }
}
Run Code Online (Sandbox Code Playgroud)

测试

public class TracerLogTest {

@Mock
InvocationContext mockContext;
@Mock
Logger mockLogger;
@InjectMocks
private TracerLog cut = new TracerLog();

@BeforeMethod
public void setup() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void logCallTest() throws Exception {
    when(mockContext.proceed()).thenReturn(true);
    when(mockContext.getMethod().getDeclaringClass().getName()).thenReturn("someClass");
    cut.logCall(mockContext);
    verify(mockContext).proceed();
}
Run Code Online (Sandbox Code Playgroud)

}

要么

@Test
public void logCallTest() throws Exception {
    when(mockContext.proceed()).thenReturn(true);
    when(mockContext.getMethod().getName()).thenReturn("someMethod");
    when(mockContext.getMethod().getDeclaringClass().getName()).thenReturn("someClass");
    cut.logCall(mockContext);
    verify(mockLogger).write(anyString());
    verify(mockContext).proceed();
}
Run Code Online (Sandbox Code Playgroud)

但是,测试因NullPointerException而失败.我知道我在反对嘲笑概念时做错了什么,但我不明白它是什么.你能否对它有所启发,并建议我如何测试这种方法?

谢谢.

jhe*_*cks 24

您需要一个Method对象和一个Class对象.根据你的评论,Mockito无法模拟一个方法,所以你需要一个真实的方法.我没有测试过这个,但我相信这会有用.代替:

when(mockContext.getMethod().getName()).thenReturn("someMethod");
when(mockContext.getMethod().getDeclaringClass().getName()).thenReturn("someClass");
Run Code Online (Sandbox Code Playgroud)

你需要:

// any method will do, but here is an example of how to get one.
Method testMethod = this.getClass().getMethod("logCallTest");

when(mockContext.getMethod()).thenReturn(testMethod);
Run Code Online (Sandbox Code Playgroud)

显然,getName()不会再返回"someMethod" getDeclaringClass().getName()并将返回此测试类的名称(在示例中),但是虽然您无法选择他们返回的内容,但他们返回的内容仍然是确定性的,因此您应该能够验证任何内容你需要.(当然,如果您需要间谍或验证是否对Method对象本身进行了调用,那么您仍然会被卡住.)