![](/img/trans.png)
[英]How to write Transactional Unit Tests for Transactional Methods in Spring?
[英]how to write unit tests for spring webflux router?
我有以下類型的 EntityRouter,現在我的問題是沒有自動連接的處理程序,我如何模擬和編寫 junit 單元測試(非集成)這樣的端點?
注意:對於 controller,這對我來說在概念上很簡單,因為如果我們使用 spring-web-mvc,我可以模擬通常在 controller 中自動裝配的服務。
public class EntityRouter {
@Bean
public RouterFunction<ServerResponse> route(EntityHandler handler) {
return RouterFunctions
.route(GET("/getAllEntities").and(accept(MediaType.APPLICATION_JSON)), handler::findAll)
.andRoute(GET("/getEntity/{id}").and(accept(MediaType.APPLICATION_STREAM_JSON)), handler::findById)
.andRoute(POST("/createEntity").and(accept(MediaType.APPLICATION_JSON)), handler::save)
.andRoute(DELETE("/deleteEntity/{id}").and(accept(MediaType.APPLICATION_JSON)), handler::delete);
}
}
如果你模擬EntityHandler
類就足夠了:
@Test
public void testRoute() {
EntityHandler mockHandler = mock(EntityHandler.class);
RouterFunction<ServerResponse> routerFunction = new EntityRouter().route(mockHandler);
// Set up a mock request
ServerRequest request = mock(ServerRequest.class);
when(request.method()).thenReturn(HttpMethod.GET);
when(request.path()).thenReturn("/getAllEntities");
when(request.headers()).thenReturn(new HttpHeaders());
// Call the router function
routerFunction.route(request).subscribe();
// Verify that the correct method on the mock handler was called
verify(mockHandler).findAll(request);
}
您可以將WebTestClient
用於基於 stream 的響應式 rest 端點。 你可以在這里找到一些例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.