問題描述
我想測試的 Java 類(稱為 ServiceCaller
)有這個:
The Java class (called ServiceCaller
) I wish to test has this:
@Autowired @Qualifier(value="serviceA")
SomeService serviceA;
@Autowired @Qualifier(value="serviceB")
SomeService serviceB;
(有一個 doWork()
方法將檢查條件并調用 A 或 B).
(there's a doWork()
method that will check a condition and call either A or B).
如何將每個服務的模擬注入到適當的變量中?
How do I inject a mock of each service into the appropriate variable?
我的 Junit 有這個:
@InjectMocks ServiceCaller classUnderTest = new ServiceCaller();
@Mock SomeService mockServiceA;
@Mock SomeService mockServiceB;
然而,當我運行測試以檢查在正確條件下調用的服務 A/B 時,我得到空指針,因為尚未注入模擬.
Yet when I run my tests to check that service A/B called under the correct condition, I get null pointers as the mock hasn't been injected.
顯然是因為對同一接口 (SomeService
) 的多個依賴項.有沒有辦法在聲明模擬服務時指定限定符?還是我需要為依賴項設置設置器并設置老式方式?
Obviously its because of multiple dependencies on the same interface (SomeService
). Is there a way to specify the qualifier when declaring the mock service? Or do I need to have setters for the dependencies and set the old fashioned way?
推薦答案
將你的 mocks 命名為 serviceA 和 serviceB 就足夠了.來自 Mockito 文檔:
It should be enough to name your mocks serviceA and serviceB. From Mockito documentation:
屬性設置器注入;模擬將首先按類型解析,然后,如果有多個相同類型的屬性,則通過匹配屬性名稱和模擬名稱.
Property setter injection; mocks will first be resolved by type, then, if there is several property of the same type, by the match of the property name and the mock name.
在你的例子中:
@InjectMocks ServiceCaller classUnderTest;
@Mock SomeService serviceA;
@Mock SomeService serviceB;
請注意,使用@InjectMocks 時無需手動創建類實例.
Note that it is not necessary to manually create class instance when using @InjectMocks.
盡管如此,我個人更喜歡使用構造函數注入依賴項.它使在測試中注入模擬變得更容易(只需使用模擬調用構造函數 - 無需反射工具或 @InjectMocks
(這很有用,但隱藏了某些方面)).此外使用 TDD 可以清楚地看到測試類需要哪些依賴項,并且 IDE 可以生成您的構造函數存根.
Nevertheless I personally prefer injecting dependencies using constructor. It makes it easier to inject mocks in tests (just call a constructor with your mocks - without reflections tools or @InjectMocks
(which is useful, but hides some aspects)). In addition using TDD it is clearly visible what dependencies are needed for the tested class and also IDE can generate your constructor stubs.
Spring Framework 完全支持構造函數注入:
Spring Framework completely supports constructor injection:
@Bean
public class ServiceCaller {
private final SomeService serviceA;
private final SomeService serviceB;
@Autowired
public ServiceCaller(@Qualifier("serviceA") SomeService serviceA,
@Qualifier("serviceB") SomeService serviceB) { ... }
...
}
可以使用以下代碼測試此代碼:
This code can be tested with:
@Mock SomeService serviceA;
@Mock SomeService serviceB;
//in a setup or test method
ServiceCaller classUnderTest = new ServiceCaller(serviceA, serviceB);
這篇關于如何注入同一接口的多個模擬的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!