Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why unit test getting failed in spring boot

I’m working on spring boot project. All things work perfectly but while unit testing saveBooking() method of controller then unit testing become failure. In Failure Trace I get java.lang.AssertionError: Response content expected:<Saved> but was:<SAVED>. This code worke perfectly in my postman but failure in unit testing.

Here down is my code:

Model

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Booking {
    private String bookingId;
    private String passangerName;
    private String flightName;
    private String source;
    private String destination;
    
    // constructor, getter and setter
}

Controller

@RestController
public class BookingController {

    @Autowired
    private BookingService bookingService;

    @PostMapping("/booking")
    public String saveBooking(@RequestBody Booking booking) {
        boolean saved = bookingService.saveBooking(booking);
        return "SAVED";

    }
}

TestController

@WebMvcTest(controllers = BookingController.class)
public class BookingControllerTest {

    @MockBean
    private BookingService bookingService;

    @Autowired
    private MockMvc mockMvc;
    
    @Test
    public void testSaveBooking() throws Exception
    {
        Mockito.when(bookingService.saveBooking(any())).thenReturn(true);
        String bookingDetails = "{\r\n"
                + "    \"bookingId\": \"AA0456\",\r\n"
                + "    \"passangerName\": \"Michael\",\r\n"
                + "    \"flightName\": \"Air American\",\r\n"
                + "    \"source\": \"California\",\r\n"
                + "    \"destination\": \"Dubai\"\r\n"
                + "}";
        RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/booking").contentType(MediaType.APPLICATION_JSON).content(bookingDetails);
        mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk()).andExpect(content().string("Saved"));
    }

}

>Solution :

SAVED != Saved

 return "SAVED";

but expect

andExpect(content().string("Saved"));

Solution 1:
Try to use an enum so you can’t misspell it

Solution 2:

check the string with .toLowerCase() when you check, so the case doesn’t matter.

Solution 3:

Use

return "SAVED";

and

andExpect(content().string("SAVED"));

so the strings match.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading