問題描述
我正在為具有 2 級(jí)依賴注入的類編寫測(cè)試用例.我對(duì) 1 級(jí)依賴注入對(duì)象使用 @Spy 注釋,我想模擬第 2 級(jí)注入.但是,我在第二級(jí)不斷收到空指針異常.有什么方法可以將模擬注入@Spy 對(duì)象?
I'm writing a test case for a Class which has a 2 level of dependency injection. I use @Spy annotation for the 1 level dependency injection object, and I would like to Mock the 2nd level of injection. However, I kept getting null pointer exception on the 2nd level. Is there any way that I inject the mock into the @Spy object?
推薦答案
Mockito 不能執(zhí)行如此棘手的注入,因?yàn)樗皇且粋€(gè)注入框架.因此,您需要重構(gòu)代碼以使其更具可測(cè)試性.使用構(gòu)造函數(shù)注入很容易做到:
Mockito cannot perform such a tricky injections as it's not an injection framework. So, you need to refactor your code to make it more testable. It's easy done by using constructor injection:
在這種情況下,您必須手動(dòng)處理模擬和注入:
In this case you have to handle the mocking and injection manually:
這篇關(guān)于Mockito 將模擬注入 Spy 對(duì)象的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!