首页 > 解决方案 > Spock 单元测试来测试 RestTemplate.postForEntity

问题描述

我是 Spock 单元测试框架的新手。我能够使用 Spock 为简单的逻辑编写单元测试用例。现在,我正在为 Rest API 编写相同的代码。

我正在使用 Spring 的 RestTemplate 来访问 GET 和 POST 请求。我在 google 中看到了一些 GET 请求的示例(如 WireMock)。但是,没有足够的信息来说明如何为 POST 请求编写测试用例。

这是我用 Junit 编写的示例代码。我必须将其转换为 Spock(我可以)。

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;

import com.github.tomakehurst.wiremock.junit.WireMockRule;

@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@ActiveProfiles(value = "integration")
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class LocalControllerTest {

  @Rule
  public WireMockRule wireMockRule = new WireMockRule(9999);

  @Before
  public void setUp() {
    mockRemoteService();
  }

  @Test
  public void testLocalServiceWithMockedRemoteService() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8080/localService", String.class);
    org.junit.Assert.assertEquals("Input : request from client endpoint, Message : mocked remote service response", response.getBody());
  }

  private void mockRemoteService() {
    stubFor(get(urlEqualTo("/remote"))
        .willReturn(aResponse()
            .withStatus(200)
            .withHeader("Content-Type", "application/json")
            .withBodyFile("remoteServiceResponse.json")));
  }

}

主要问题是,即使我编写了测试用例,调用实际上是发生在服务上(位于我的本地主机上),我不希望它发生。有没有办法在本地模拟数据并使用 Spock 框架调用虚拟端点以进行 POST 请求?我对模拟一个虚拟端点知之甚少。

非常感谢您的帮助。

谢谢。

标签: groovyspock

解决方案


推荐阅读