无法在 Spring Reactive 中模拟我的服务方法
Cannot able to Mock my service's methods in Spring Reactive
我正在尝试使用 Spring 反应式开发聊天应用程序。基本上,我有一个 CommentRestController,它有 postComment 和列表方法。 - 我已经删除了 list 方法和其他一些不必要的和不相关的方法,因为我现在不关注它们 - 在这里;
@RestController
@RequiredArgsConstructor
@RequestMapping("/chat/comment")
public class CommentRestController {
private final CommentService commentService;
private final ChannelService channelService;
@PostMapping("/add")
public Mono<AddCommentResponse> postComment(@Valid @RequestBody Comment comment, ServerWebExchange serverWebExchange) {
String userName = serverWebExchange.getAttribute("username");
return commentService.save(userName, comment);
}
}
现在,我正在尝试编写此控制器的文档测试。我遇到的问题是,我无法模拟我的 commentService 的 save 方法。它实际上是在模拟实例而不是方法。
这是我的文档测试 class。
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"token-validation-service.url = http://localhost:8080/token-validation-service/", "profanity.similarity = 0.9"})
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
public class CommentRestControllerDocumentationTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
private WebTestClient webTestClient;
@Autowired
private CommentRestController commentRestController;
@MockBean
CommentService commentService;
@MockBean
ChannelService channelService;
@MockBean
ServerWebExchange serverWebExchange;
@MockBean
TokenValidationServiceClient tokenValidationServiceClient;
@MockBean
OperationResult operationResult;
@MockBean
AddCommentResponse addCommentResponse;
private RequestHeadersSnippet requestHeaderSnippet = requestHeaders(headerWithName("X-Auth-Token").description("Authentication Access Token"));
private FieldDescriptor responseReturnCode = fieldWithPath("meta.return_code").description("Operation return code");
private FieldDescriptor responseMessage = fieldWithPath("meta.message").description("Operation message");
private FieldDescriptor idField = fieldWithPath("id").description("id of the comment");
private FieldDescriptor authorField = fieldWithPath("author").description("Author of the comment");
private FieldDescriptor commentField = fieldWithPath("text").description("Comment itself");
private FieldDescriptor channelIdField = fieldWithPath("channelId").description("Channel Id of the comment");
private FieldDescriptor timestampField = fieldWithPath("timestamp").description("Timestamp of the comment");
private FieldDescriptor usernameField = fieldWithPath("username").description("Username of the comment, to check who commented");
private FieldDescriptor isBadField = fieldWithPath("isBad").description("Profanity check for comment");
@Before
public void setUp() {
webTestClient = WebTestClient.bindToController(commentRestController)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
@Test
@WithMockUser
public void postComment() throws Exception {
String stubName = "postComment";
Comment comment = new Comment();
comment.setId("1");
comment.setAuthor("orcun");
comment.setChannelId("123");
comment.setText("This is a test method");
comment.setIsBad(false);
comment.setTimestamp("1479249799770");
comment.setUsername("5332109939");
operationResult.setReturnCode(ChatServiceConstants.SUCCESS_CODE);
operationResult.setMessage(ChatServiceConstants.SUCCESS_MESSAGE);
addCommentResponse.setOperationResult(operationResult);
when(serverWebExchange.getAttribute("username")).thenReturn("5332109939");
String userName = serverWebExchange.getAttribute("username");
when(commentService.save(userName, comment)).thenReturn(Mono.just(addCommentResponse));
webTestClient.post().uri("/chat/comment/add")
.header("X-Auth-Token", "8811-1113")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(comment))
.exchange()
.expectStatus().isOk()
.expectBody()
.consumeWith(document(stubName,
requestFields(idField, authorField, commentField, timestampField,
channelIdField, usernameField, isBadField),
responseFields(responseReturnCode, responseMessage)));
}
}
当我 运行 执行此操作时,我看到一个错误,指出响应正文为空。这是:
org.springframework.restdocs.snippet.SnippetException: Cannot document response fields as the response body is empty
at org.springframework.restdocs.payload.AbstractFieldsSnippet.verifyContent(AbstractFieldsSnippet.java:201)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:157)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:83)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:206)
at org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.lambda$document[=13=](WebTestClientRestDocumentation.java:81)
at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultBodyContentSpec.lambda$consumeWith(DefaultWebTestClient.java:496)
at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:194)
at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultBodyContentSpec.consumeWith(DefaultWebTestClient.java:496)
at com.turkcell.tvplus.tvpluschat.rest.CommentRestControllerDocumentationTest.postComment(CommentRestControllerDocumentationTest.java:136)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.restdocs.JUnitRestDocumentation.evaluate(JUnitRestDocumentation.java:63)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=13=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
当我打开 target/generated-snippets 的路径时,我看到生成了该方法的文档,但响应- fields.adoc 为空。
我通过调试会话检查了代码,我意识到我无法 mock 我的 commentService.save()方法。
任何帮助将不胜感激。
提前致谢。
问题是响应式开发需要与时间无关的应用程序。这就是为什么像 twitter 或聊天这样的应用程序正在使用它。在大多数像我这样的情况下,预期的内容甚至无法回到它所属的位置。
这就是为什么为响应式项目编写单元测试比您想象的要难一些。
我上面的问题的答案仅此而已。希望对大家有所帮助。
我正在尝试使用 Spring 反应式开发聊天应用程序。基本上,我有一个 CommentRestController,它有 postComment 和列表方法。 - 我已经删除了 list 方法和其他一些不必要的和不相关的方法,因为我现在不关注它们 - 在这里;
@RestController
@RequiredArgsConstructor
@RequestMapping("/chat/comment")
public class CommentRestController {
private final CommentService commentService;
private final ChannelService channelService;
@PostMapping("/add")
public Mono<AddCommentResponse> postComment(@Valid @RequestBody Comment comment, ServerWebExchange serverWebExchange) {
String userName = serverWebExchange.getAttribute("username");
return commentService.save(userName, comment);
}
}
现在,我正在尝试编写此控制器的文档测试。我遇到的问题是,我无法模拟我的 commentService 的 save 方法。它实际上是在模拟实例而不是方法。
这是我的文档测试 class。
@RunWith(SpringRunner.class)
@SpringBootTest(properties = {"token-validation-service.url = http://localhost:8080/token-validation-service/", "profanity.similarity = 0.9"})
@AutoConfigureRestDocs(outputDir = "target/generated-snippets")
public class CommentRestControllerDocumentationTest {
@Rule
public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation();
private WebTestClient webTestClient;
@Autowired
private CommentRestController commentRestController;
@MockBean
CommentService commentService;
@MockBean
ChannelService channelService;
@MockBean
ServerWebExchange serverWebExchange;
@MockBean
TokenValidationServiceClient tokenValidationServiceClient;
@MockBean
OperationResult operationResult;
@MockBean
AddCommentResponse addCommentResponse;
private RequestHeadersSnippet requestHeaderSnippet = requestHeaders(headerWithName("X-Auth-Token").description("Authentication Access Token"));
private FieldDescriptor responseReturnCode = fieldWithPath("meta.return_code").description("Operation return code");
private FieldDescriptor responseMessage = fieldWithPath("meta.message").description("Operation message");
private FieldDescriptor idField = fieldWithPath("id").description("id of the comment");
private FieldDescriptor authorField = fieldWithPath("author").description("Author of the comment");
private FieldDescriptor commentField = fieldWithPath("text").description("Comment itself");
private FieldDescriptor channelIdField = fieldWithPath("channelId").description("Channel Id of the comment");
private FieldDescriptor timestampField = fieldWithPath("timestamp").description("Timestamp of the comment");
private FieldDescriptor usernameField = fieldWithPath("username").description("Username of the comment, to check who commented");
private FieldDescriptor isBadField = fieldWithPath("isBad").description("Profanity check for comment");
@Before
public void setUp() {
webTestClient = WebTestClient.bindToController(commentRestController)
.configureClient()
.filter(documentationConfiguration(restDocumentation))
.build();
}
@Test
@WithMockUser
public void postComment() throws Exception {
String stubName = "postComment";
Comment comment = new Comment();
comment.setId("1");
comment.setAuthor("orcun");
comment.setChannelId("123");
comment.setText("This is a test method");
comment.setIsBad(false);
comment.setTimestamp("1479249799770");
comment.setUsername("5332109939");
operationResult.setReturnCode(ChatServiceConstants.SUCCESS_CODE);
operationResult.setMessage(ChatServiceConstants.SUCCESS_MESSAGE);
addCommentResponse.setOperationResult(operationResult);
when(serverWebExchange.getAttribute("username")).thenReturn("5332109939");
String userName = serverWebExchange.getAttribute("username");
when(commentService.save(userName, comment)).thenReturn(Mono.just(addCommentResponse));
webTestClient.post().uri("/chat/comment/add")
.header("X-Auth-Token", "8811-1113")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(comment))
.exchange()
.expectStatus().isOk()
.expectBody()
.consumeWith(document(stubName,
requestFields(idField, authorField, commentField, timestampField,
channelIdField, usernameField, isBadField),
responseFields(responseReturnCode, responseMessage)));
}
}
当我 运行 执行此操作时,我看到一个错误,指出响应正文为空。这是:
org.springframework.restdocs.snippet.SnippetException: Cannot document response fields as the response body is empty
at org.springframework.restdocs.payload.AbstractFieldsSnippet.verifyContent(AbstractFieldsSnippet.java:201)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:157)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:83)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:206)
at org.springframework.restdocs.webtestclient.WebTestClientRestDocumentation.lambda$document[=13=](WebTestClientRestDocumentation.java:81)
at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultBodyContentSpec.lambda$consumeWith(DefaultWebTestClient.java:496)
at org.springframework.test.web.reactive.server.ExchangeResult.assertWithDiagnostics(ExchangeResult.java:194)
at org.springframework.test.web.reactive.server.DefaultWebTestClient$DefaultBodyContentSpec.consumeWith(DefaultWebTestClient.java:496)
at com.turkcell.tvplus.tvpluschat.rest.CommentRestControllerDocumentationTest.postComment(CommentRestControllerDocumentationTest.java:136)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:83)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.restdocs.JUnitRestDocumentation.evaluate(JUnitRestDocumentation.java:63)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=13=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
当我打开 target/generated-snippets 的路径时,我看到生成了该方法的文档,但响应- fields.adoc 为空。
我通过调试会话检查了代码,我意识到我无法 mock 我的 commentService.save()方法。
任何帮助将不胜感激。 提前致谢。
问题是响应式开发需要与时间无关的应用程序。这就是为什么像 twitter 或聊天这样的应用程序正在使用它。在大多数像我这样的情况下,预期的内容甚至无法回到它所属的位置。
这就是为什么为响应式项目编写单元测试比您想象的要难一些。
我上面的问题的答案仅此而已。希望对大家有所帮助。