【发布时间】:2019-06-07 10:00:53
【问题描述】:
我正在尝试在 Spring Boot 中使用 Mockito 来编写一个“模仿”对我的 ElasticSearch 实例的调用的单元测试。现在因为在单元测试中你不应该打扰外部资源,因此使用 Mockito,我停止了我的 ElasticSearch 实例。问题是我的 UnitTest 一直在尝试连接到我的 ElasticSearch 实例,因此它通过说“连接被拒绝”而失败。这是我的测试:
import com.google.common.net.HttpHeaders;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.util.Base64Utils;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ElasticSearchConnectionTest {
@Autowired
private MockMvc mvc;
@Value("${elasticsearch.user}")
private String user;
@Value("${elasticsearch.password}")
private String password;
private String myjson = "{ \"order\": \n" + "{ \n" + "\"id\":\"dbId\",\n" + "\"status\":\"completed\",\n" + "} \n" + "}";
@Test
public void contextLoads() throws Exception {
this.mvc.perform(post("/order")
.contentType(MediaType.APPLICATION_JSON)
.content(myjson)
.header(HttpHeaders.AUTHORIZATION, "Basic " +Base64Utils.encodeToString((user+":"+password).getBytes())))
.andExpect(status().is2xxSuccessful());
}
}
错误信息说:java.net.ConnectException: Connection refused
我使用 Java Low Level Rest Client 来调用 ElasticSearch
【问题讨论】:
-
你发现了吗?
标签: spring-boot elasticsearch mockito