Wednesday 15 September 2010

spring mvc - mvc controller test with session attribute -



spring mvc - mvc controller test with session attribute -

i'm trying test method signature:

@autowired httpsession http_session; @requestmapping(method=requestmethod.get, value="/search/findbyname") public @responsebody list<map> search(@requestparam(value="name", required=true) string name){ integer user_id = http_session.getattribute("userinfo"); }

userinfo class contains informations user , set in session scope when user logged in.but when seek test :

@runwith(springjunit4classrunner.class) @webappconfiguration @contextconfiguration(locations = { "classpath:/meta-inf/applicationcontext.xml"}) public class usercontrollertest { private mockmvc mockmvc; @autowired private webapplicationcontext webapplicationcontext; @before public void setup() { mockitoannotations.initmocks(this); this.mockmvc = mockmvcbuilders.webappcontextsetup(this.webapplicationcontext).build(); } @test public void usertest() throws exception { mockmvc.perform(mockmvcrequestbuilders.get("/search/findbyname").param("name", "bob")) .anddo(print()) .andexpect(mockmvcresultmatchers.status().isok()); }

the problem userinfo class attribute set in method when seek access in method got nullpointerexception , , autowiring httpsession got new session each method have test.

what should session attribute, method doesn't take session parameter , , each test create webapplicationcontext new session.

try :

hashmap<string, object> sessionattr = new hashmap<string, object>(); sessionattr.put("userinfo", "xxxxxxxx"); mockmvc.perform(mockmvcrequestbuilders.get("/search/findbyname").sessionattrs(sessionattr).param("name", "bob")) .anddo(print()) .andexpect(mockmvcresultmatchers.status().isok());

spring-mvc controller attributes junit4 httpsession

No comments:

Post a Comment