I am new to Unit Testing. After referring google, I created a Test class to test my Controller as follows:
@RunWith(SpringRunner.class)
@WebMvcTest(PromoController.class)
public class PromoApplicationTests {
@Autowired
protected MockMvc mvc;
@MockBean PromoService promoService;
protected String mapToJson(Object obj) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
@Test
public void applyPromotionTest_1() throws Exception {
String uri = "/classPath/methodPath";
List<Cart> cartLs = new ArrayList<Cart>();
// added few objects to the list
String inputJson = mapToJson(cartLs);
MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
.contentType(MediaType.APPLICATION_JSON).content(inputJson)).andReturn();
int status = mvcResult.getResponse().getStatus();
assertEquals(200, status);
String actual = mvcResult.getResponse().getContentAsString();
String expected = "{\"key1\":val1, \"key2\":\"val 2\"}";
assertEquals(expected, actual, true);
}
}
I have the following Controller and service Class :
@RequestMapping("/classPath")
@RestController
public class PromoController {
@Autowired
PromoService promoService;
@PostMapping("/methodPath")
public PromoResponse applyPromo(@RequestBody List<Cart> cartObj) {
PromoResponse p = promoService.myMethod(cartObj);
return p;
}
}
@Component
public class PromoServiceImpl implements PromoService{
@Override
public PromoResponse myMethod(List<Cart> cartList) {
// myCode
}
}
When I debugged my unit test, p object in the controller was null. I am getting status as 200 but not the expected JSON response
What am I missing here?