問題描述
我有一個包含 new()
調用以實例化 LoginContext
對象的舊類:
I have a legacy class that contains a new()
call to instantiate a LoginContext
object:
public class TestedClass {
public LoginContext login(String user, String password) {
LoginContext lc = new LoginContext("login", callbackHandler);
}
}
我想使用 Mockito 來模擬 LoginContext
來測試這個類,因為它要求在實例化之前設置 JAAS 安全性內容,但我不確定如何在不更改 code>login()
方法來外部化 LoginContext
.
I want to test this class using Mockito to mock the LoginContext
as it requires that the JAAS security stuff be set up before instantiating, but I'm not sure how to do that without changing the login()
method to externalize the LoginContext
.
是否可以使用 Mockito 來模擬 LoginContext
類?
Is it possible using Mockito to mock the LoginContext
class?
推薦答案
對于未來我會推薦 Eran Harel 的回答(重構將 new
移動到可以模擬的工廠).但是,如果您不想更改原始源代碼,請使用非常方便且獨特的功能:sies.來自文檔:
For the future I would recommend Eran Harel's answer (refactoring moving new
to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:
您可以創建真實對象的間諜.當您使用 spy 時,會調用 real 方法(除非方法被存根).
You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).
應該小心偶爾使用真正的間諜,例如在處理遺留代碼時.
Real spies should be used carefully and occasionally, for example when dealing with legacy code.
在你的情況下,你應該寫:
In your case you should write:
TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);
這篇關于使用 Mockito 在其中調用 new() 測試類的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!