Spring boot application fails on mockmvc test -
i have simple controller test looks this
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = cuponzaapiapplication.class) @webappconfiguration public class usercontrollertest { private mockmvc mockmvc; @autowired protected webapplicationcontext wac; @autowired userrepository userrepository; @before public void setup(){ mockmvc = mockmvcbuilders.webappcontextsetup(wac).build(); } @test public void createuser() throws exception{ cuponzauser user = new cuponzauser("some@test.com", "firstname", "lastname"); objectwriter jackson = new objectmapper().writer().withdefaultprettyprinter(); mockmvc.perform(post("/user/add").content(jackson.writevalueasstring(user)).contenttype(mediatype.application_json)) .anddo(print()) .andexpect(status().isok()) .andexpect(content().contenttype("application/json")); }
however fails saying following java.lang.assertionerror: content type not set
here controller
@restcontroller public class usercontroller { @autowired userrepository userrepository; @requestmapping(value = "/user/add",method = requestmethod.post,produces={mediatype.application_json_value}) public void adduser(@requestbody cuponzauser user, httpservletresponse response){ if(user ==null){ response.setstatus(httpstatus.bad_request.value()); return; }else{ user.setcreationdate(new date()); user.setlastseendate(new date()); userrepository.save(user); //response.addheader("content-type", mediatype.application_json_value); return; } }
i dont want manually add content type header each response , , thought "produces" annotation should take care of this
any ideas?
the issue you're not returning anything. response body empty.
in way makes sense, there no content, point in defining content-type
? setting accept
header won't anywhere. furthermore, should able reproduce same behaviour outside of unit tests too, i.e. it's not issue unit test/mock setup.
you either:
- return content
- consider returning 204 (no content), if don't want return (still wouldn't give
content-type
header make clear there no content) - add header manually in workaround commented out in question
Comments
Post a Comment