首页 > 解决方案 > 测试@ControllerAdvice NO REST

问题描述

我的问题是:如何测试在抛出 EmailNotSendException 时是否使用了 EmailNotSendHandler?或第二个问题:解决这个异常处理谜题的正确术语是什么?

**目标:测试是否在抛出 EmailNotSendException 异常时调用了 EmailNotSendHandler 类。没有休息任何控制器**

我对编程很陌生,不知道正确的术语。我正在尝试使用 Spring 学习纯单元测试和异常处理,以及 Spring Boot 应用程序的内部。我已经用谷歌搜索了如何测试。每个搜索结果都归结为:编写 REST 控制器,以便您可以对 REST 控制器进行 REST 调用。我不想编写 REST 控制器,因为它超出了学习目标的范围。基本上任何包含 REST 的东西都超出了范围。

@ControllerAdvice 注释类。

@ControllerAdvice
@Slf4j
public class EmailNotSendHandler {
    @ExceptionHandler(EmailNotSendException.class)
    private void processEmailNotSendExceptions(EmailNotSendException e){
        log.info("[QUATRO] Error handling? {}", e.getMessage());
    }
}

异常类。

public class EmailNotSendException extends RuntimeException {
     public EmailNotSendException(String error) {
         super("test: " + error);
     }
}

电子邮件服务类

@Service
public class EmailService {
    private final JavaMailSender emailSenderContainer;

    @Value("email@email.email")
    private String receivingEmailAdress;

    public void sendSimpleMessage(String emailText) {
        SimpleMailMessage message = new SimpleMailMessage();

        if (emailTekst.isEmpty()) {
            return;
        }
        message.setTo(receivingEmailAdress);
        message.setSubject("Error");
        message.setText(emailText);
        emailSenderContainer.send(message);
    }
}

单元测试

@Test()
public void testSimpleMailMessageSendFailed() {
    doThrow(new EmailNotSendException("")).when(emailServiceMocked).sendSimpleMessage("");
    emailServiceMocked.sendSimpleMessage("");
}

标签: javaspring-bootjunit

解决方案


推荐阅读