[英]How to mock objects initialized in constructor using an external method call?
final HttpClient httpClient;
final HttpUtils httpUtils;
@Autowired
public SampleConstructor(HttpUtils httpUtils) {
this.httpClient = ApacheHttpSingleton.getHttpClient();
this.httpUtils = httpUtils;
}
所以我有這個 class 有兩個我正在使用自動裝配構造函數初始化的對象。 在為此 class 編寫 JUnit 測試時,我必須模擬這兩個對象。 HttpUtils object 很簡單。 但是,它是 HttpClient object 我遇到了麻煩 mocking。
@Mock
HttpUtils mockHttpUtils;
@Mock
HttpClient mockHttpClient;
@InjectMocks
SampleConstructor mockService;
上述方法適用於 HttpUtils,但不適用於 HttpClient。 有人可以幫助我如何為 HttpClient 注入模擬的 object 嗎?
創建一個包私有構造函數,它將兩個對象都作為其參數。 將您的單元測試放在同一個 package 中(但在 src/test/java/ 中),以便它可以訪問該構造函數。 將模擬發送到該構造函數:
final HttpClient httpClient;
final HttpUtils httpUtils;
@Autowired
public SampleConstructor(HttpUtils httpUtils) {
this(ApacheHttpSingleton.getHttpClient(), httpUtils);
}
// For testing
SampleConstructor(HttpClient httpClient, HttpUtils httpUtils) {
this.httpClient = httpClient;
this.httpUtils = httpUtils;
}
然后在你的測試中:
@Mock
HttpUtils mockHttpUtils;
@Mock
HttpClient mockHttpClient;
SampleConstructor c = new SampleConstructor(mockHttpClient, mockHttpUtils);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.