我想为以InvocationContext为参数的方法编写一个单元测试。更具体地说,这是该方法的签名和要领。如何获得单元测试的InvocationContext的实例
@AroundInvoke
public Object autoLogMethodCall(final InvocationContext context) throws Exception {
String className = context.getClass().getSimpleName();
String packageName = context.getClass().getPackage().getName();
String methodName = context.getMethod().getName();
// Some logging stuff that is the target of actual testing
}
正如你看到的,它是一个拦截器方法,我打算用做某些方法调用一些基本的日志记录。
然后我有单元测试,我想测试记录的消息将被正确格式化。但问题是我无法创建一个InvocationContext的实例作为测试参数传递。
我试过下面的嘲弄。
@RunWith(PowerMockRunner.class)
public class AutoLoggingTest extends TestCase {
@Test
public void testAutoLogger() {
Logger log = new MyLogger(); // This is an implementation of org.apache.logging.log4j.Logger, which will hold the generated messages to check at the test
InvocationContext mockContext = PowerMockito.mock(InvocationContext.class);
Class clazz = AutoLoggingTest.class;
// The row causing the error 'MissingMethodInvocation'
PowerMockito.when(mockContext.getClass()).thenReturn(clazz);
try {
InterceptingClass ic = new InterceptingClass();
ic.setLogger(log);
ic.autoLogMethodCall(mockContext);
MyLogger myLogger = (MyLogger) ic.getLogger();
assertEquals(2, myLogger.getMessages().size());
} catch (Exception e) {
e.printStackTrace();
fail("Should not cause an exception in any case");
}
}
// Check the actual messages based on the information given in mocked InvocationContext object
}
但它不起作用。
原因:
Tests in error: AutoLoggingTest.testAutoLogger:25 » MissingMethodInvocation.
when() requires an argument which has to be 'a method call on a mock'.).
如何做正确的嘲讽任何意见?