Home > Software design >  Unit test for restTemplate.postForEntity causes ResourceAccessException
Unit test for restTemplate.postForEntity causes ResourceAccessException

Time:03-12

I made a method that just checks if a url that we have running on a port is working.

public boolean isBackendRunning() throws URISyntaxException, IOException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<Object> entity = new HttpEntity<Object>(headers);

    //ResponseEntity<String> out = restTemplate.postForEntity(new URI("https://localhost:8443"), entity, String.class);
    ResponseEntity<String> response
            = restTemplate.getForEntity("https://localhost:8443", String.class);

    return true;

  }

The issue is when running our unit test I am always getting org.springframework.web.client.ResourceAccessException Caused by: java.net.ConnectException

public static MockWebServer mockBackEnd;
      @Autowired Controller Controller;
      MissionController mc = Mockito.mock(Controller.class);
    
      @Mock
      RestTemplate mockRestTemplate;
    
      @Mock public ResponseEntity<String> responseEntity;

      @Test
  public void GetRequestTest() throws IOException, URISyntaxException {
    Mockito.when(mockRestTemplate.getForEntity(any(), eq(String.class))).thenReturn(responseEntity);
    Mockito.when(mock.isBackendRunning()).thenReturn(true);
    mockBackEnd.enqueue(new MockResponse().setBody(response).addHeader(content, app_json));
    assertEquals(
        ...
            .getMissionJSON(MockOAuth2AuthenticationToken.createAuthCountry())
            .toString());
  }

In the code sample above I have tried mocking the get restTemplate to just return a result, and mocking the method. I thought that this would prevent the method from actually running the code and just get me a result so we can do the unit test. This is not the case.

How do I handle this check without getting these errors? OpenConnection will not work with how we have a program set up. I have tried so many different ways to get this working with restTemplate.

CodePudding user response:

It looks like you have a MissionController class with a RestTemplate dependency, and you want to inject a mock of that dependency into a MissionController instance to unit test the isBackendRunning method.

@RunWith(MockitoJUnitRunner.class)
public class MissionControllerTest {
  @Mock
  private RestTemplate mockRestTemplate;
  @Mock 
  private ResponseEntity<String> responseEntity;
  @InjectMocks
  private MissionController missionController = new MissionController();
  @Test
  public void GetRequestTest() throws Exception {
   Mockito.when(mockRestTemplate.getForEntity(any(), 
      any(Class.class))).thenReturn(responseEntity);
   boolean running = missionController.isBackendRunning();

   assertTrue(running);
  }
}
  • Related