Reputation: 503
while doing Content-negotiation testing mock GET returns with null in response body although response status is 200.
java.lang.AssertionError: Response header 'Content-Type'
Expected :application/json;charset=UTF-8
Actual :null
here is full test class code. I want to verify that content type is json.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
Controller controller;
@Test
public void test() throws Exception {
mockMvc.perform(get("/query?mediaType=json"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE));
}}
here is my controller's endpoint.
@RestController
public class Controller {
@RequestMapping(value = "/query", produces = {"application/json", "application/xml"}, method = RequestMethod.GET)
public @ResponseBody ResultSet getResults(
final HttpServletRequest request
) throws Throwable {
// logic ...
SearchService search = (SearchService) context.getBean("search");
ResultSet result = search.getResults();
return result;
}
Any thoughts why Body would return as null?
Upvotes: 0
Views: 1647
Reputation: 10632
The issue is with your Controller definition in your Test class. As you are testing your Controller
, you should be using an actual instance of it. Get you mockMvc
instance for this Controller
as below (you can do it in your @Before
annotated setup method):
mockMvc = MockMvcBuilders.standaloneSetup(new Controller()).build();
Upvotes: 1