SpringBootTest MockMvc:andExpect 状态不抛出

SpringBootTest MockMvc: andExpect status not throwing

我正在学习为 SpringBoot REST 编写集成测试 api,当我发送垃圾数​​据时,测试仍然通过。我希望“.andExpect(status().isCreated())”抛出异常并使测试失败,但事实并非如此?

@SpringBootTest
@AutoConfigureMockMvc
class BorrowerApplicationIntegrationTests {

  @Autowired
  private MockMvc mockMvc;

  @Autowired
  private ObjectMapper objectMapper;

  @Autowired
  private BookLoanDAO bookLoanDao;

  @Autowired
  private BorrowerController controller;


  @Test
  @Transactional
  void checkoutBook() throws Exception {
    BookLoanId bookLoanId = new BookLoanId(2, 2, 2); // This book does not exist in this branch

    mockMvc.perform(post("/borrowers/book/checkout")
            .contentType("application/json")
            .content(objectMapper.writeValueAsString(bookLoanId)))
            .andExpect(status().isCreated()); // The returned response is a 404 yet the test passes

    List<BookLoan> bookLoans = bookLoanDao.findAll().stream()
            .filter(l -> (
              l.getId().getBorrower().getId() == 1
              &&
              l.getId().getBook().getId() == 1
              &&
              l.getDateIn() == null))
            .collect(Collectors.toList());

    assertThat(bookLoans.size() > 0);
  }
}

当测试运行时,控制台打印:

org.springframework.web.server.ResponseStatusException: 404 NOT_FOUND "Book with ID 2 is not available at branch with ID 2."

为什么在返回错误响应的情况下测试仍然通过?

有很多事情可以尝试。

手动设置 MockMvc。我在 @AutoConfigureMockMvc 注释和 @Autowire MockMvc mockMcv 错误设置 bean 方面遇到了问题。

在每次测试前和拆卸后设置 http servlet。老实说,我已经忘记了它们的用途,但它们解决了一些问题,结果默认为 200/201 状态。

post()请求使用MockMvcRequestBuilders导入;可能是使用了错误的导入。


@ContextConfiguration // Replace @AutoConfigureMockMvc

    @Autowired
    private WebApplicationContext context;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();

        HttpServletRequest mockRequest = new MockHttpServletRequest();
        ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(mockRequest);
        RequestContextHolder.setRequestAttributes(servletRequestAttributes);
    }

    @After
    public void tearDown() throws Exception {
        RequestContextHolder.resetRequestAttributes();
   }

    @Test
    public void testGetCv_NotFound() throws Exception {



    RequestBuilder request = MockMvcRequestBuilders
                 .post("/borrowers/book/checkout")
                .contentType("application/json")
                .content(objectMapper.writeValueAsString(bookLoanId));

        mockMvc.perform(request)
                .andExpect(status().isNotFound());
    }