电子邮件发送失败测试返回 HTTP 200 而不是 500

问题描述 投票:0回答:1

我正在编写一个测试用例来验证

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

任何有关如何解决此问题的建议将不胜感激!

spring-boot spring-mvc spring-security mockito spring-test
1个回答
0
投票

在您的测试中,您的

ccEmails
bccEmails
字段为
null
。但是,
ArgumentMatchers.anyList()
仅匹配非空列表,如 API 文档中所述:

任何 非空

List

自 Mockito 2.1.0 起,仅允许非 null

List
。由于这是一个可为 null 的引用,因此建议的 match
null
包装器 API 为
isNull()
。我们认为这一变化将使测试工具比 Mockito 1.x 更安全。

因此,正如 API 文档中提到的,您应该使用

isNull()
。或者,您可以使用
any()
:

doThrow(new EmailSendingException("Failed to send email"))
    .when(emailOperations)
    .sendBasicEmail(
        anyString(), 
        isNull(), // Change this
        isNull(), // Change this
        anyString(),
        anyString(),
        anyBoolean());
© www.soinside.com 2019 - 2024. All rights reserved.