spring-boot - 使用放心框架测试服务器发送事件
问题描述
我正在使用 Spring Boot 并放心测试我的 REST 服务
我有一个休息控制器,例如
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
Flux<String> getFlux() {
...
如何正确断言响应正文?
我认为该值以“数据:”的形式返回,用于在一次输出后终止的流。
我也不知道在尝试异步影响数据时如何测试流的实际工作?
解决方案
反应测试
您应该使用 WebTestClient 来测试您的反应式服务。
这是一个例子
服务方式:
public Flux<GithubRepo> listGithubRepositories(String username, String token) {
return webClient.get()
.uri("/user/repos")
.header("Authorization", "Basic " + Base64Utils
.encodeToString((username + ":" + token).getBytes(UTF_8)))
.retrieve()
.bodyToFlux(GithubRepo.class);
}
考试:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class WebclientDemoApplicationTests {
@Autowired
private WebTestClient webTestClient;
@Test
public void test2GetAllGithubRepositories() {
webTestClient.get().uri("/api/repos")
.accept(MediaType.APPLICATION_JSON_UTF8)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
.expectBodyList(GithubRepo.class);
}
}
请在此处找到示例https://www.callicoder.com/spring-5-reactive-webclient-webtestclient-examples/
标准 MVC 测试
模拟MVC
您可以使用模拟环境来测试控制器类,而无需真正启动 servlet 容器:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MockMvcExampleTests {
@Autowired
private MockMvc mvc;
@Test
public void exampleTest() throws Exception {
this.mvc.perform(get("/")).andExpect(status().isOk())
.andExpect(content().string("Hello World"));
}
}
使用正在运行的服务器:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class RandomPortTestRestTemplateExampleTests {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void exampleTest() {
String body = this.restTemplate.getForObject("/", String.class);
assertThat(body).isEqualTo("Hello World");
}
}
请阅读官方文档中有关 Spring Boot 测试的更多信息
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing
推荐阅读
- ios - 如何删除 main.storyboard 的元素
- reactjs - 反应如何替换整个 url 位置而不是路径名堆叠
- android-studio - 在成功构建之前,设计编辑器不可用...此错误显示在我的 android studio activity_main.xml 中
- c# - EFCore 2.2.6 与 5.0.8 无跟踪
- python - Matplotlib 导入错误:TypeError:预期的 str、字节或 os.PathLike 对象,而不是 WindowsPath
- javascript - 根据其他列中的值更新 DynamoDB 中的项目
- powershell - 如何在 VS 代码中保留每个项目的 PowerShell 命令(历史记录键)?
- javascript - php。如果 Cookie 存在,请执行此操作 - 否则执行此操作
- flutter - Flutter - Cloudinary 如何获取上传的图片网址?
- typo3 - TYPO3 从 v9 升级到 V10 延迟加载错误