Java 监视实例变量并在实例函数get调用时返回值
我试图模拟类实例,然后在调用实例函数时返回模拟对象,但结果是,它实际调用了函数 这是我的密码:Java 监视实例变量并在实例函数get调用时返回值,java,junit,mockito,Java,Junit,Mockito,我试图模拟类实例,然后在调用实例函数时返回模拟对象,但结果是,它实际调用了函数 这是我的密码: AuthenticationSessionModel authSessionCookie = new AuthenticationSessionManager(session) .getCurrentAuthenticationSession(realm, client, tabId); 我的测试代码是: AuthenticationSessionManager spyAuth
AuthenticationSessionModel authSessionCookie =
new AuthenticationSessionManager(session)
.getCurrentAuthenticationSession(realm, client, tabId);
我的测试代码是:
AuthenticationSessionManager spyAuthSessionManager =
Mockito.spy(new AuthenticationSessionManager(session));
doReturn(authenticationSessionModel)
.when(spyAuthSessionManager)
.getCurrentAuthenticationSession(any(), any(), anyString());
它实际调用getCurrentAuthenticationSession(),并返回空指针异常。在测试中,您创建了一个间谍,并存根了一些行为。 但是你不能在测试代码中使用间谍 相反,在测试代码中创建一个新的AuthenticationSessionManager 您需要重新构造代码,并:
- 在测试对象外部创建AuthenticationSessionManager
- 将其传递给被测对象。构造函数是首先想到的东西
有了这些更改,在测试中用spy替换真实的AuthenticationSessionManager就变得很简单了。您应该使用
Mockito.mock
而不是Mockito.spy
如果您想避免调用真实实例,您所说的测试对象外部是什么意思?你能给我一个例子吗?你检索AuthSessionOkie的代码是某个对象(测试对象)中某个方法(测试中的方法)的一部分。将authenticationSessionManager
作为此对象的字段和构造函数的参数。将authenticationSessionManager传递给构造函数。