[英]How to mock @Value field using mockito
我正在嘗試測試一個方法,但是當我的測試方法調用實際方法時,由於存在@Value 字段,實際方法總是接收@Value 字段下定義的值,即null。 您可以查看以下實際方法和測試方法的代碼:
實際方法
public class IndexService {
@Value("${elasticsearch.index}")
private String index;
public boolean index(String id, String json, String index) {
try {
createIndex();
return true;
} catch (IOException e) {
log.warn("Exception in indexing data {}", e.getMessage());
}
return false;
}
private void createIndex() throws IOException {
CreateIndexRequest request = new CreateIndexRequest(index);
}
}
下面是我的測試方法:
@Test
public void IndexServiceIndex() throws IOException {
CreateIndexRequest request1 = new CreateIndexRequest(index);
request1.source("{\"name\":true}",XContentType.JSON);
Mockito.when(indicesClient.create(request1,RequestOptions.DEFAULT))
.thenReturn(createIndexResponse);
Boolean indexser = indexService.index("65","{\"name\":molly}","1");
}
下面是CreateIndexRequest class
方法:
public CreateIndexRequest(String index) {
if (index == null) {
throw new IllegalArgumentException("The index name cannot be null.");
} else {
this.index = index;
}
}
發生的事情是,當我的測試方法調用實際方法indexService.index("65","{\"name\":molly}","1");
,然后控制轉到actual method
,私有方法createIndex
正在注入上面定義為@Value("${elasticsearch.index}") private String index;
的index
值; . 因此在CreateIndexRequest method
中,它總是評估為 null 並拋出異常IllegalArgumentException("The index name cannot be null.")
。
我嘗試使用ReflectionTestUtils.setField
但我的項目中沒有org.springframework.test.util.ReflectionTestUtils
所需的依賴項。 還有其他方法可以模擬@Value 字段嗎?
你根本不知道。 通常不鼓勵使用字段注入,因為它使測試代碼變得更加復雜。 要測試您嘗試測試的任何內容,請使用
可能還有很多其他人。 我認為1和2是最可行的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.