繁体   English   中英

在测试中初始化变量(MockMVC)

[英]Initialize a variable in a test (MockMVC)

我正在尝试使用MockMVC(Spring框架)运行2个测试。

  • 第一个添加用户。 添加用户后,将生成并返回一个userID
  • 第二个应该从此userID删除添加的用户。

在测试类的开头,我有以下变量: String userID;

这是我创建用户(工作)的测试。 创建用户之后,我将从响应中获得该用户的生成ID。

@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 just take the ID from the response
    Matcher matcher = Pattern.compile("\\d+").matcher(result.getResponse().getContentAsString());
    matcher.find();

    this.userID = matcher.group();       
    System.out.println(userID); //Correctly print the generated ID
}

现在,我尝试删除这个可怜的家伙:

@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 is null :-(
}

问题在于userID在第一个测试中已正确初始化,但在第二个测试中为null (这是一个类变量)。 我不明白为什么。

您能帮我运行那些测试吗?如果可以的话,请解释一下为什么第二个测试中userID == null吗?

谢谢!

创建用于设置的gettersetter方法并获取值userID,例如: void setUserId(matcher.group()) ---->现在,在设置了userId之后,应该将它inside it_adds_a_new_user()

还添加一个gette方法,通过调用getUserId()获得值----->应该在it_deletes_the_new_user()内部

因为我不知道您程序的结构,所以只给您一个解决问题的想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM