'mockMvc always return 200 status - Test Exception handling with SpringBoot

ReceiptController endpoint

    @GetMapping(value = "/{id}")
    public ReceiptOverdue getReceiptById(@PathVariable int id) {
        return receiptService.getReceipt(id);
    }

ReceiptService

public ReceiptOverdue getReceiptOverdue(Integer id) {
        return receiptRepository.findReceiptById(id).map(MGReceipt::toModel).orElseThrow(() -> ReceiptNotFoundException.getException());
    }

And the ReceiptNotFoundException class

public class ReceiptNotFoundException extends ResponseStatusException {

    public ReceiptNotFoundException(HttpStatus status) {
        super(status);
    }

    public static ReceiptNotFoundException getException() {
        return new ReceiptNotFoundException(HttpStatus.NOT_FOUND);
    }
}

when testing manually I get a 404

{
  "timestamp": 1649076257786,
  "status": 404,
  "error": "Not Found",
  "path": "/api/receipt/10"
}

But when using mockMvc in the Test case I get always 200 status

Expected :404
Actual   :200
@WebMvcTest(controllers = ReceiptController.class)
class ReceiptOverdueControllerTest {


    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ReceiptService receiptService;


    @BeforeEach
    void setUp() {
    }

    @AfterEach
    void tearDown() {
    }
   
    @Test 
    void whenReceiptNotFoundReturn404() throws Exception {
        var mvcResult = mockMvc.perform(get("/api/receipt/10"))
                .andDo(print())
                .andExpect(status().isNotFound());
    }   
} 

BUT if I throw the exception in the controller the test will pass ! Is there an issue on how I throw the exception in the service ? or the problem is in my mockMvc Test ? Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source