我正在编写一个测试用例来验证
EmailSendingException
是否会产生 HTTP 500 响应。但是,当抛出异常时,我的测试仍然返回状态 200,而不是预期的 500。
这是我的代码的相关部分:
测试用例:
@Test
@WithMockUser(username = "admin", roles = {"ADMIN"})
void testSendBasicEmail_Failure() throws Exception {
// Arrange
BasicEmailRequest request = new BasicEmailRequest();
request.setToEmail("[email protected]");
request.setSubject("Test Subject");
request.setBody("Test Body");
request.setIsHtml(false);
doThrow(new EmailSendingException("Failed to send email")).when(emailOperations)
.sendBasicEmail(anyString(), anyList(), anyList(), anyString(), anyString(), anyBoolean());
// Act & Assert
mockMvc.perform(post("/api/email/sendBasic")
.with(csrf())
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(request)))
.andExpect(status().isInternalServerError()) // Expecting HTTP 500
.andExpect(content().string("Failed to send email. Please try again later."));
verify(emailOperations, times(1)).sendBasicEmail(
"[email protected]", null, null, "Test Subject", "Test Body", false);
}
控制器:
@PostMapping("/sendBasic")
@PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
public ResponseEntity<String> sendBasicEmail(@Valid @RequestBody BasicEmailRequest request) throws EmailSendingException {
logger.info("Sending basic email: {}", request);
emailOperations.sendBasicEmail(
request.getToEmail(),
request.getCcEmails(),
request.getBccEmails(),
request.getSubject(),
request.getBody(),
request.getIsHtml()
);
return ResponseEntity.ok("Email sent successfully.");
}
异常处理:
@ExceptionHandler(EmailSendingException.class)
public ResponseEntity<ErrorResponse> handleEmailSendingException(EmailSendingException ex) {
logger.error("Email sending failed: {}", ex.getMessage(), ex);
ErrorResponse errorResponse = new ErrorResponse("EMAIL_SENDING_FAILED", ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
}
测试失败并显示以下错误消息:
java.lang.AssertionError: Status expected:<500> but was:<200>
Expected :500
Actual :200
当抛出
EmailSendingException
时,我预计会出现 HTTP 500 状态,但相反,我收到了带有“电子邮件发送成功”的 HTTP 200 响应。可能是什么原因造成的?我该如何解决?
Environment:
Spring Boot: 3.3.4
Spring Security
Spring Test
JUnit 5
Mockito
任何有关如何解决此问题的建议将不胜感激!
在您的测试中,您的
ccEmails
和 bccEmails
字段为 null
。但是,ArgumentMatchers.anyList()
仅匹配非空列表,如 API 文档中所述:
任何 非空
。List
自 Mockito 2.1.0 起,仅允许非 null
。由于这是一个可为 null 的引用,因此建议的 matchList
包装器 API 为null
。我们认为这一变化将使测试工具比 Mockito 1.x 更安全。isNull()
因此,正如 API 文档中提到的,您应该使用
isNull()
。或者,您可以使用 any()
:
doThrow(new EmailSendingException("Failed to send email"))
.when(emailOperations)
.sendBasicEmail(
anyString(),
isNull(), // Change this
isNull(), // Change this
anyString(),
anyString(),
anyBoolean());