我正在编写一个测试用例来验证是否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
当抛出时,我期望 HTTP 500 状态EmailSendingException
,但我收到的是 HTTP 200 响应,其中显示“电子邮件发送成功”。这可能是什么原因造成的?我该如何修复?
Environment:
Spring Boot: 3.3.4
Spring Security
Spring Test
JUnit 5
Mockito
如能得到有关如何解决此问题的任何建议,我们将不胜感激!
在您的测试中,您的
ccEmails
和bccEmails
字段是null
。但是,ArgumentMatchers.anyList()
仅匹配非空列表,如API 文档所述:结果是,由于不匹配,模拟永远不会抛出您的异常。因此,正如 API 文档所述,您可以使用
isNull()
。或者,您可以使用any()
:我个人的看法是,既然你已经有一个
verify()
确认确切调用的语句,我更喜欢any()
在语句的任何地方使用doThrow()
。如果你使用了错误的匹配器,你可以用verify()
API 比用更容易地检测到它when()
。