title: Mockito ElasticSearch Unit test in Spring Boot
body: <p>I am trying to use Mockito in Spring Boot in order to write a Unit Test that "imitates" a call to my ElasticSearch instance. Now since in Unit Testing you are not supposed to bother external resources, and thus using Mockito, I have my ElasticSearch instance stopped. The problem is that my UnitTest keeps trying to connect to my ElasticSearch instance so it fails by saying "Connection refused". Here is my test: </p>
  
  <pre><code>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());
    }
  }
  </code></pre>
  
  <p>The error message says: <code>java.net.ConnectException: Connection refused</code></p>
  
  <p>I am using using <a href="https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-low.html" rel="nofollow noreferrer">Java Low Level Rest Client</a> for calling calls to ElasticSearch</p>