首页 > 解决方案 > 当预期为 404 时,Spring Boot 控制器测试返回 200

问题描述

我正在尝试测试控制器层。在这种情况下,通过 id 查找客户。我有一个通过测试,它工作正常并返回200状态代码。现在,我想要一个失败的测试用例场景。所以当我得到 /customers/1测试应该失败并返回一个404,但它正在返回200。使用 Junit5, Spring-boot:2.5.3

@WebMvcTest
public class CustomerControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private CustomerService customerService;

    @Test
    @DisplayName("GET /customers/1 -Failure")
    void findCustomerByIdShouldReturn_404() throws Exception {
        when(customerService.findById(1L)).thenReturn(Optional.empty());

        RequestBuilder requestBuilder= MockMvcRequestBuilders.get("/customers/{id}",1);

        mockMvc.perform(requestBuilder)
                .andExpect(status().isNotFound()).andReturn();
    }
}

错误:

      HTTP Method = GET
      Request URI = /customers/1
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.prabhakar.customer.controller.CustomerController
           Method = com.prabhakar.customer.controller.CustomerController#findCustomerById(Long)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/json"]
     Content type = application/json
             Body = null
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:<404> but was:<200>
Expected :404
Actual   :200

这是我的控制器和服务类。

@RestController
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping(path = "/customers/{id}")
    public Optional<Customer> findCustomerById(@PathVariable("id") Long id){
        return customerService.findById(id);
    }
}



@Service
public class CustomerService {
    @Autowired
    private CustomerRepository customerRepository;

    
    public Optional<Customer> findById(Long id) {
        return customerRepository.findById(id);
    }

}

标签: javaspring-bootmockitojunit5

解决方案


您的控制器没有您希望测试的逻辑。这是您的控制器应如何实现以按照您希望的方式运行

@RestController
public class CustomerController {

    @Autowired
    private CustomerService customerService;

    @GetMapping(path = "/customers/{id}")
    public ResponseEntity<Customer> findCustomerById(@PathVariable("id") Long id){
        Optional<Customer> optCust = customerService.findById(id);
        if (optCust.isPresent()){
            return ResponseEntity.ok(optCust.get());
        } else {
            return ResponseEntity.notFound().build()
        }
    }
}

推荐阅读