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
。
我知道關於野外注入是邪惡的所有爭論,但我更感興趣知道是否有辦法解決這個問題,而不改變Base
和Child
類注入它們的屬性?
謝謝!
是的,不要使用Spring來進行注射。然後創建模擬並在您的測試設置中注入它們,但是您希望。 – duffymo
你能詳細解釋一下嗎? 我可以創建模擬,但不能注入它們。如果我使用'@InjectMocks'來注入mock,那麼'Child'類的屬性是'null',因爲它們使用構造函數注入。我無法使用構造函數來初始化被測試的類,因爲我沒有辦法從測試中傳遞'Base'類的屬性。 – Mubin
包括你的測試用例。 –