I am currently writing a JUnit test case for a controller in my application which returns a object (a URL). I am trying to assert the expected and the actual URL to be the same. There are 2 things happening here when I inspect the MvcResult result:
mockResponse has a status code of 200.
In ModelAndView, the model does have the expected url value but when I try to assert the result using
result.getResponse().getContentAsString()
, the assertion fails as the result is empty.
What I have already tried:
While debugging, I see the control moving to the service which means that the values were properly mocked and the expected url got returned to the result (as it was present in the ModelAndView when inspected).
I have tried to give the expected url as a json object, used object mapper to read it and then tried a JSONAssert but the result is still empty.
@RunWith(SpringJUnit4ClassRunner.class) public class StudentControllerTest { private static final String CACHE_URL= "cacheurl"; @Mock StudentCacheService studentCacheService; @InjectMocks StudentCacheController studentCacheController; private MockMvc mockMvc; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(studentCacheController).build(); } @Test public void testGetScoresUrl() throws Exception { Mockito.when(studentCacheService.getStudentUrl("123", "science")) .thenReturn(new StudentUrl(CACHE_URL)); MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.get("/student/123/scores") .header("subject", "science").contentType(MediaType.APPLICATION_JSON)).andExpect(status().is2xxSuccessful()) .andReturn(); Assert.assertEquals(CACHE_URL, result.getResponse().getContentAsString()); } }
My Controller class is as below:
@Controller
@RequestMapping("/student")
public class StudentCacheController {
@Autowired
StudentCacheService studentCacheService;
@GetMapping(path = "/{studentId}/scores",produces = MediaType.APPLICATION_JSON_VALUE)
public StudentUrl getScores(@PathVariable String studentId, @RequestHeader(value = "subject", required = true) String subject) throws Exception {
return studentCacheService.getStudentUrl(studentId, subject);
}
}
The response is as below:
MockHttpServletResponse:
Status = 200
Error message = null
Forwarded URL = student/123/scores
Included URL = []
ModelAndView:
model = ModelMap
key = studentUrl
value = StudentUrl
url = "cacheurl"
I am receiving this error : org.junit.ComparisonFailure: expected:<[cacheurl]> but was:<[]>
Any help appreciated. Thanks!