groovy - 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 请求?我对模拟一个虚拟端点知之甚少。
非常感谢您的帮助。
谢谢。
解决方案
推荐阅读
- java - 将Java 类作为其余模板的主体传递
- python - 模型表格未保存
- java - 无法使用 Java 中的 In 子句从 DB 获取记录(Spring 存储库)
- spring-boot - 无法使用传入消息端点处理程序详细信息调用侦听器方法:rabbitMQ
- python - 从卷积网络中删除 Sequential 后,我得到:“TypeError:'Tensor' object is not callable”
- typescript - 是否可以将元组的键映射到数字文字的联合?
- c# - C# 仅使用 do while 以 2 个不同的间隔打印数字
- ios - 在 ViewController 出现之前加载数据/图形/背景的方法
- javascript - 剑道网格截断小数
- eclipse - Eclipse,mvn eclipse:clean eclipse:eclipse,错误:找不到或加载主类