Java 如何使用mockito模拟@Value字段

Java 如何使用mockito模拟@Value字段,java,spring-boot,unit-testing,junit,mockito,Java,Spring Boot,Unit Testing,Junit,Mockito,我试图测试一个方法,但当我的测试方法调用实际方法时,由于@Value字段存在,实际方法总是接收@Value字段下定义的值,即null。您可以在下面查看实际方法和测试方法的代码: 实际方法 public class IndexService { @Value("${elasticsearch.index}") private String index; public boolean index(String id, String json, Stri

我试图测试一个方法,但当我的测试方法调用实际方法时,由于@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类
方法:

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”)
,然后控件转到
实际方法
,私有方法
createIndex
正在注入
index
值,该值在上面定义为
@value(${elasticsearch.index}”)私有字符串索引。因此,在
CreateIndexRequest方法中,它总是计算为null并抛出异常
IllegalArgumentException(“索引名不能为null”)


我尝试使用
ReflectionTestUtils.setField
,但是
org.springframework.test.util.ReflectionTestUtils
所需的依赖项不在我的项目中。有没有其他方法来模拟@Value字段?

你根本没有。一般来说,使用字段注入是不可取的,因为它会使测试代码变得更加复杂。要测试您试图测试的内容,请使用

  • 构造函数注入-您可以在构造函数参数上设置@Value,并且可以通过构造函数设置测试值
  • setter注入-用@Value注释setter方法。它在容器中的工作原理完全相同,如何在测试中使用它是显而易见的
  • 使用@TestProperties-但这将修复整个测试类的值
  • 使用反射-这允许您甚至改变最终字段,但是如果涉及AOP和代理,这可能不简单

  • 可能还有很多其他的。我认为1和2是最可行的方法。

    看看
    @SpringBootTest
    ,它有一个
    属性
    参数。你能给我一些链接,让我阅读如何使用它吗?还有没有其他方法可以仅使用mockito解决问题?答案是不要。将类更改为使用构造函数注入,然后只需调用
    new
    并将值作为普通参数传递给它。这可能很有用:Thankyou@chrylis cautiouslyoptimistic-,我将尝试这种方法。