Home > database >  SpringBoot Integration Testing - TestRestTemplate null
SpringBoot Integration Testing - TestRestTemplate null

Time:02-18

I am using Springboot 2.1.2 and junit-jupiter-api-5.3.2 and I am doing integration testing.

My test case is this:

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.ril.vms.hawkeye.otp.dto.SendOTPRequestDTO;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@SpringBootTest(classes = MyApplication.class,
        webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("sit")
public class OtpControllerIntegrationTest
{
    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void sendOtpTest() throws Exception {

        SendOTPRequest otpRequest = new SendOTPRequestDTO();
        otpRequest.setClientId("default2");
        otpRequest.setTag("tag");
        otpRequest.setMobileNumber("9999999999");
        ResponseEntity<String> responseEntity = this.restTemplate
                .postForEntity("http://localhost:"   port   "/sendOtp", otpRequest, String.class);
        assertEquals(201, responseEntity.getStatusCodeValue());

    }
}

But I am getting java.lang.NullPointerException at below line.

ResponseEntity<String> responseEntity = this.restTemplate ...

Need help

CodePudding user response:

try this template

public ArrayList<ABC> lovApi(LovsRequestDto reqObj) {

HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "application/json");

HttpEntity<ABCDto> entity = new HttpEntity<ABCDto>(reqObj, headers);

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);

String postUrl = "http://80.111.23.23.33333.....";

ResponseEntity<LovsResponse> postResponse = restTemplate.exchange(postUrl, HttpMethod.POST, entity, LovsResponse.class);
return postResponse.getBody().getLovs_response_details().getLovList();

}

CodePudding user response:

try to create a new restTemplate bean in sendOtpTest mehtods. you get null point because this.restTemplate is not be instation; wish help you;

  • Related