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
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.