簡體   English   中英

如何使用 mockito 模擬 @Value 字段

[英]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. 構造函數注入 - 您可以在構造函數參數上 @Value,並且可以通過構造函數放置測試值
  2. setter injection - 使用 @Value 注釋 setter 方法。 它在容器中的工作方式完全相同,如何在測試中使用它是顯而易見的
  3. 使用@TestProperties - 但這將修復整個測試 class 的值
  4. 使用反射——這甚至可以讓你改變最終字段,但是如果涉及到 AOP 和代理,這可能不會簡單地工作

可能還有很多其他人。 我認為1和2是最可行的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM