[英]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.