JUnit 和Spring 5:Spring 5 全面接纳了函数式范例,并支持JUnit 5 及其新的函数式测试风格。还提供了对JUnit 4 的向后兼容性,以确保不会破坏旧代码。
Spring 5 的测试套件通过多种方式得到了增强,但最明显的是它对JUnit 5 的支持。现在可以在您的单元测试中利用Java 8 中提供的函数式编程特性。以下代码演示了这一支持:
JUnit 5 全面接纳了Java 8 流和lambda 表达式
@Test
void givenStreamOfInts_SumShouldBeMoreThanFive() {
assertTrue(Stream.of(20, 40, 50)
.stream()
.mapToInt(i -> i)
.sum() > 110, () -> "Total should be more than 100");
}
迁移到JUnit 5:如果您对升级到JUnit 5 持观望态度,Steve Perry 的分两部分的深入剖析教程将说服您冒险尝试。
Spring 5 继承了JUnit 5 在Spring TestContext Framework 内实现多个扩展API 的灵活性。举例而言,开发人员可以使用JUnit 5 的条件测试执行注解@EnabledIf 和@DisabledIf 来自动计算一个SpEL (Spring Expression Language) 表达式,并适当地启用或禁用测试。借助这些注解,Spring 5支持以前很难实现的复杂的条件测试方案。Spring TextContext Framework 现在能够并发执行测试。
使用Spring WebFlux 执行集成测试
Spring Test 现在包含一个WebTestClient,后者支持对Spring WebFlux 服务器端点执行集成测试。WebTestClient 使用模拟请求和响应来避免耗尽服务器资源,并能直接绑定到WebFlux 服务器基础架构。
WebTestClient 可绑定到真实的服务器,或者使用控制器或函数。在下面的代码中,WebTestClient 被绑定到localhost:
绑定到localhost 的WebTestClient
WebTestClient testClient = WebTestClient
.bindToServer()
.baseUrl("http://localhost:8080")
.build();
将WebTestClient 绑定到RouterFunction
RouterFunction bookRouter = RouterFunctions.route(
RequestPredicates.GET("/books"),
request -> ServerResponse.ok().build()
);
WebTestClient
.bindToRouterFunction(bookRouter)
.build().get().uri("/books")
.exchange()
.expectStatus().isOk()
.expectBody().isEmpty();