2017-03-27 63 views
3

我有以下類的設置。春天:有場和構造函數注入的類的單元測試

class Base { 
    @Autowired 
    private BaseService service; //No getters & setters 
    .... 
} 

@Component 
class Child extends Base { 
    private final SomeOtherService otherService; 

    @Autowired 
    Child(SomeOtherService otherService) { 
    this.otherService = otherService; 
    } 
} 

我正在爲Child類寫單元測試。 如果我使用@InjectMocks那麼otherService出現爲空。如果我在測試的設置中使用Child類的構造函數,那麼Base類中的字段出現爲null

我知道關於野外注入是邪惡的所有爭論,但我更感興趣知道是否有辦法解決這個問題,而不改變BaseChild類注入它們的屬性?

謝謝!

+0

是的,不要使用Spring來進行注射。然後創建模擬並在您的測試設置中注入它們,但是您希望。 – duffymo

+0

你能詳細解釋一下嗎? 我可以創建模擬,但不能注入它們。如果我使用'@InjectMocks'來注入mock,那麼'Child'類的屬性是'null',因爲它們使用構造函數注入。我無法使用構造函數來初始化被測試的類,因爲我沒有辦法從測試中傳遞'Base'類的屬性。 – Mubin

+0

包括你的測試用例。 –

回答

3

只是這樣做:

public class Test { 
    // Create a mock early on, so we can use it for the constructor: 
    OtherService otherService = Mockito.mock(OtherService.class); 

    // A mock for base service, mockito can create this: 
    @Mock BaseService baseService; 

    // Create the Child class ourselves with the mock, and 
    // the combination of @InjectMocks and @Spy tells mockito to 
    // inject the result, but not create it itself. 
    @InjectMocks @Spy Child child = new Child(otherService); 

    @Before 
    public void before() { 
     MockitoAnnotations.initMocks(this); 
    } 
} 

應的Mockito做正確的事。

+0

@InjectMocks和@Spy的組合告訴mockito注入結果,但不是自己創建它。「 - 這是關鍵。萬分感謝!! – Mubin