java - 使用 MockMvc Http Status 错误测试 @ControllerAdvice

标签 java spring spring-boot testing junit

我无法在 Spring Boot 应用程序中通过 MockMvc 测试。

我的 ControllerAdvice 看起来像:

@ControllerAdvice
@Slf4j
public class ExceptionHandlers extends BaseExceptionHandler {

    public ExceptionHandlers() {
        super(log);
    }

    @ResponseBody
    @ExceptionHandler(RunNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorResponse handleRunNotFoundController(final RunNotFoundException ex) {
        log.error("Run not found thrown", ex);
        return new ErrorResponse(LocalDateTime.now(), "RUN_NOT_FOUND", ex.getMessage(), HttpStatus.NOT_FOUND.value());

    }
}

我有两个测试:

@RunWith(SpringRunner.class)
@WebMvcTest(RunController.class)
public class RunControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private RunService runService;

//    @Before
//    public void setup() {
//        this.mvc = MockMvcBuilders.standaloneSetup(runService)
//                .setControllerAdvice(new ExceptionHandlers())
//                .build();
//    }

    @Test
    public void getRunsTestCorrectValues() throws Exception {

        List<Run> list = prepareRunList();
        when(runService.getRuns()).thenReturn(list);

        mvc.perform(get("/api/runs")
                .contentType("application/json"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(1)))
                .andExpect(jsonPath("$[0]").exists())
                .andExpect(jsonPath("$[0]").isNotEmpty())
                .andExpect(jsonPath("$[0].id").value(1))

    }

    @Test
    public void getRunsTestRunsNotFoundException() throws Exception {
        given(runService.getRuns()).willReturn(Collections.emptyList());

        mvc.perform(get("/api/runs")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isNotFound());
    }
}

在这种情况下,当我 setup() 注释测试 getRunsTestCorrectValues() 通过并且 getRunsTestRunsNotFoundException() 失败时:

enter image description here

在第二种情况下,当我取消注释 setup() 并重新运行测试时,我得到 getRunsTestCorrectValues() 失败,而 getRunsTestRunsNotFoundException() 通过与:

enter image description here

我认为与setup()有关。有人有什么想法吗?

最佳答案

当您 mock runService 时,您应该简单地保留您的测试用例, 所以你应该像这样修改第二个,以便抛出异常。

given(runService.getRuns()).willThrow(new RunNotFoundException("Not Found"));

关于java - 使用 MockMvc Http Status 错误测试 @ControllerAdvice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61307129/

相关文章:

Spring Boot SSL 客户端

spring - 如何在 Spring Boot 中注册新的集合工厂

java - Spring Data (Hibernate) 动态 WHERE 子句

java - 使用canvas向JFrame添加其他组件

java - 用Java编写简单的RTF文件

java - 在点击时使用 fragment 进行卡片 View 时, Activity Intent 不起作用

java - 使用 Spring JdbcTemplate 进行多个数据库操作

java - 在heroku上运行spring boot应用程序时出现"Unable to read TLD from JAR file"

nginx - 使用 Spring Cloud OAuth2 的 SSL/代理问题

java - 套接字异常 : TOO MANY OPEN FILES