使用JUnit 5 执行条件和并发测试
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();?
總結
以上是生活随笔為你收集整理的使用JUnit 5 执行条件和并发测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Web MVC 支持最新的
- 下一篇: 包清理和弃用