在Fake类的方法中,可以设置一个Invocation类对象,在该方法被调用时,JMockit会为这个对象传值。这种机制的意义是Fake类可以接触到真实类。因此,Fake类的方法可以得到调用参数,调用次数等信息。
@Test
public void invocation() throws Exception {
final Subject testSubject = new Subject();
new MockUp<LoginContext>() {
@Mock
void $init(Invocation invocation, String name, Subject subject)
{
assertNotNull(name);
assertSame(testSubject, subject);
// Gets the invoked instance.
LoginContext loginContext = invocation.getInvokedInstance();
// Verifies that this is the first invocation.
assertEquals(1, invocation.getInvocationCount());
}
@Mock
void login(Invocation invocation)
{
// Gets the invoked instance.
LoginContext loginContext = invocation.getInvokedInstance();
// getSubject() returns null until the subject is authenticated.
assertNull(loginContext.getSubject());
}
@Mock
void logout(Invocation invocation)
{
// Gets the invoked instance.
LoginContext loginContext = invocation.getInvokedInstance();
assertSame(testSubject, loginContext.getSubject());
}
};
LoginContext theFakedInstance = new LoginContext("test", testSubject);
theFakedInstance.login();
theFakedInstance.logout();
}