簡體   English   中英

如何為RestTemplate postForObject方法編寫Mockito Junit

[英]How to write mockito junit for Resttemplate postForObject method

我正在嘗試將消息列表發布到其余的api。 如何為以下方法postJSONData編寫Mockito Junit:

public class PostDataService{

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private Environment env;

    private HttpEntity<String> httpEntity;

    private HttpHeaders httpHeaders;

    private String resourceURL = null;

    public PostDataService(){
    httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-Type", "application/json");
    }

    public void postJSONData(List<String> data){
    try
    {
    resourceURL = env.getProperty("baseURL") + env.getProperty("resourcePath");
    httpEntity = new HttpEntity<String>(data.toString(), httpHeaders);
    String response = restTemplate.postForObject(resourceURL, httpEntity, String.class);
    }
    catch (RestClientException e) {
            LOGGER.info("ErrorMessage::" + e.getMessage());
            LOGGER.info("ErrorCause::" + e.getCause());
        }
    } 


}

請幫我怎么寫。

您可以使用Mockito執行以下操作:

  • 使用RestTemplateEnvironment創建postData的實例
  • 對這些設置期望值,以使``postJSONData`調用能夠完成
  • 驗證RestTemplate是否正確調用

postJSONData方法不使用restTemplate.postForObject()響應,因此就測試此方法而言,您能做的最好的事情就是驗證用正確的參數調用了restTemplate.postForObject()

這是一個例子:

@RunWith(MockitoJUnitRunner.class)
public class PostDataTest {

    @Mock
    private RestTemplate restTemplate;
    @Mock
    private Environment env;

    @InjectMocks
    private PostData postData;

    @Test
    public void test_postJSONData() {
        String baseUrl = "theBaseUrl";
        String resourcePath = "aResourcePath";

        Mockito.when(env.getProperty("baseURL")).thenReturn(baseUrl);
        Mockito.when(env.getProperty("resourcePath")).thenReturn(resourcePath);

        List<String> payload = new ArrayList<>();

        postData.postJSONData(payload);

        // it's unclear from your posted code what goes into the HttpEntity so
        // this approach is lenient about its expectation
        Mockito.verify(restTemplate).postForObject(
                Mockito.eq(baseUrl + resourcePath),
                Mockito.any(HttpEntity.class),
                Mockito.eq(String.class)
        );

        // assuming that the HttpEntity is constructed from the payload passed 
        // into postJSONData then this approach is more specific
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        Mockito.verify(restTemplate).postForObject(
                Mockito.eq(baseUrl + resourcePath),
                Mockito.eq(new HttpEntity<>(payload.toString(), headers)),
                Mockito.eq(String.class)
        );
    }
}

附帶說明; postData是類的不尋常名稱,並且OP中提供的postJSONData方法不會編譯; 它引用的是meterReadings而不是data

您可以使用Wiremock模擬服務器。 這是專門用於此工作的模擬框架。

將以下依賴項添加到您的pom.xml中:

<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
    <version>2.12.0</version>
</dependency>

在測試中添加以下規則:

@Rule
public WireMockRule wireMockRule = new WireMockRule(); // default port is 8080

然后,您應該在application.properties (或其他位置)中定義baseUrlresourcePath屬性。 記住,服務器將在本地主機上運行。

之后,您應該為resourcePath模擬HTTP響應:

stubFor(get(urlEqualTo(resourcePath))
            .withHeader("Accept", equalTo("application/json"))
            .willReturn(aResponse()
                .withStatus(200)
                .withHeader("Content-Type", "application/json")
                .withBody(content)));

然后,您可以執行postJSONData方法:

postData.postJSONData();

最后,您可以驗證對服務器的請求是否正確。

verify(postRequestedFor(urlMatching(resourcePath))
        .withRequestBody(matching(expectedBody))
        .withHeader("Content-Type", matching("application/json")));

暫無
暫無

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

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