【问题标题】:NullPointerException thrown during junit test without @SpringBootTest annotation, but not with the annotation在没有 @SpringBootTest 注释的 junit 测试期间抛出 NullPointerException,但没有注释
【发布时间】:2021-12-02 06:30:09
【问题描述】:

当我删除 @SpringBootTest 注释时,我在此测试期间收到 NullPointerException:

@SpringBootTest
@RunWith(MockitoJUnitRunner.class)
public class ExceptionInterceptorTests {

      private AysUserProvisException aysUserProvisException =
          new AysUserProvisException("Failed","True", "Failed to create user. User already exists.", null);

      @InjectMocks @Spy ExceptionInterceptor exceptionInterceptorSpy;
      
      @Test
      void testAysUserProvisException_generateCorrectResponseSchema() {
        ResponseEntity<Object> response = exceptionInterceptorSpy.handleAysUserProvisException(aysUserProvisException);
        
        AysUserProvisResponse exceptionResponse =
            new AysUserProvisResponse(
                "Failed", "True", "Failed to create user. User already exists.", null);
        ResponseEntity<Object> expected =
            new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);

        assertEquals(response.getBody(), expected.getBody());
      }

尝试执行此方法时抛出:

    @ControllerAdvice
    public class ExceptionInterceptor extends ResponseEntityExceptionHandler {
        
        @ExceptionHandler(AysUserProvisException.class)
          public final ResponseEntity<Object> handleAysUserProvisException(AysUserProvisException ex) {
            AysUserProvisResponse exceptionResponse =
                new AysUserProvisResponse(
                    ex.getStatus(), ex.getIsErrorOccurred(), ex.getMessage(), ex.getError());
            return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
        }

这是 AysUserProvisResponse 类:

public class AysUserProvisResponse {
    
    private String status;
    private String isErrorOccurred;
    private String message;
    private Error  error = new Error();
    
    
    public AysUserProvisResponse() {
        super();
    }

    public AysUserProvisResponse(String status, String isErrorOccurred, String message, Error error) {
        super();
        this.status = status;
        this.isErrorOccurred = isErrorOccurred;
        this.message = message;
        this.error = error;
    }

@SpringBootTest 注解如何避免这个异常?为什么有必要?

【问题讨论】:

  • 顺便说一句:@RunWith(MockitoJUnitRunner.class) 行可以删除。这是一个 JUnit 4 构造,在这里被忽略了。 Mocking 仍然有效,因为在使用 @SpringBootTest 时默认打开它。

标签: spring-boot spring-mvc nullpointerexception junit5 spring-test


【解决方案1】:

如果您在代码中使用注释或尝试注入 bean,则必须上传 spring 上下文。

尝试模拟您的 Exception 类的依赖项并将模拟注入到 ExceptionInterceptor 类中

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多