监视实例变量和 return 实例函数 get 调用时的值
Spying on instance variable and return the value when instance function get calls
我正在尝试模拟 class 实例,然后在我们调用实例函数时 return 模拟对象,但结果是,它对函数进行了实际调用。
这是我的代码:
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() 并且 return 出现空指针异常
在测试中,您创建了一个间谍,并存根了一些行为。
但是你不要在被测代码中使用那个间谍。
相反,在被测代码中您创建了一个新的 AuthenticationSessionManager。
您需要重构您的代码并且:
- 在被测对象之外创建 AuthenticationSessionManager。
- 将其传递给被测对象。构造函数是第一个想到的。
通过这些更改,在测试中用间谍替换真正的 AuthenticationSessionManager 变得微不足道。
我正在尝试模拟 class 实例,然后在我们调用实例函数时 return 模拟对象,但结果是,它对函数进行了实际调用。
这是我的代码:
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() 并且 return 出现空指针异常
在测试中,您创建了一个间谍,并存根了一些行为。 但是你不要在被测代码中使用那个间谍。
相反,在被测代码中您创建了一个新的 AuthenticationSessionManager。
您需要重构您的代码并且:
- 在被测对象之外创建 AuthenticationSessionManager。
- 将其传递给被测对象。构造函数是第一个想到的。
通过这些更改,在测试中用间谍替换真正的 AuthenticationSessionManager 变得微不足道。