我想爲以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'.).
如何做正確的嘲諷任何意見?