java - Spring MVC Controller Test passing due to not finding model attribute -


i have created home controller below. controller fetches 5 dummy posts have created in "postrepository" class through postservice class.

@controller public class homecontroller {      @autowired     postservice postservice;      @requestmapping("/")     public string gethome(model model){         model.addattribute("post", postservice);          return "home";     } } 

i have implemented following test..

@runwith(springjunit4classrunner.class) @contextconfiguration(classes = {webconfig.class}) @webappconfiguration public class controllertest {      @test //test home controller     public void testhomepage() throws exception{         homecontroller homecontroller = new homecontroller();         mockmvc mockmvc = standalonesetup(homecontroller).build();          mockmvc.perform(get("/"))                 .andexpect(view().name("home"))                 .andexpect(model().attributedoesnotexist("post"));     }  } 

the test has passed. attribute should exist.

you mixing 2 incompatible features of spring's testing support.

if instantiate controller within test, need use mockmvcbuilders.standalonesetup().

if using spring testcontext framework (i.e., @contextconfiguration, etc.), need use mockmvcbuilders.webappcontextsetup().

thus, following appropriate configuration test.

@runwith(springjunit4classrunner.class) @contextconfiguration(classes = webconfig.class) @webappconfiguration public class controllertest {      @autowired     webapplicationcontext wac;      @autowired     postservice postservice;      @test     public void testhomepage2() throws exception {         mockmvc mockmvc = mockmvcbuilders.webappcontextsetup(wac).build();          mockmvc.perform(get("/"))                 .andexpect(view().name("home"))                 .andexpect(model().attribute("post",postservice));     } } 

regards,

sam (author of spring testcontext framework)


Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -