簡體   English   中英

Spring 啟動集成測試-TestRestTemplate null

[英]Spring Boot Integration Testing - TestRestTemplate null

我正在使用Spring Boot 2.1.2junit-jupiter-api-5.3.2 ,我正在進行集成測試。

我的測試用例是這樣的:

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());

    }
}

但我在下面的行中收到java.lang.NullPointerException

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

試試這個模板

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();

}

嘗試在 sendOtpTest 方法中創建一個新的 restTemplate bean。 你得到 null 點,因為 this.restTemplate 沒有安裝; 希望對你有幫助;

暫無
暫無

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

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