java - Initialize a variable in a test (MockMVC) -


i'm trying run 2 tests mockmvc (spring framework).

  • the first 1 add user. when user added, userid generated, , returned.
  • the second should delete added user userid.

at start of test class, have variable: string userid;

here test create user (it works). after creating user, response generated id user.

@test public void it_adds_a_new_user() throws exception {     mvcresult result = mockmvc         .perform(post("/users")             .contenttype(mediatype.application_json)             .content("user infos, in json..."))         .andexpect(status().isok())         .andreturn();     //next lines take id response     matcher matcher = pattern.compile("\\d+").matcher(result.getresponse().getcontentasstring());     matcher.find();      this.userid = matcher.group();            system.out.println(userid); //correctly print generated id } 

now, try delete poor guy:

@test public void it_deletes_the_new_user() throws exception {     system.out.println(userid); //it prints null!     mockmvc.perform(delete("/users/" + userid)         .contenttype(mediatype.application_json)     .andexpect(status().isok()); //400 because userid null :-( } 

the problem userid correctly initialized in first test, null in second (it class variable). don't understand why.

can me running tests, , if possible explain me why userid == null on second test ?

thanks!

create getter , setter method set , value userid like: void setuserid(matcher.group())---->should inside it_adds_a_new_user() have setted userid

add 1 gette method also, value calling getuserid()----->should inside it_deletes_the_new_user()

since dont know structuer of program giving idea solve problem.


Comments