繁体   English   中英

如何保存声明为类变量并在JUnit中的测试内初始化的任何对象

[英]How to save any object which is declared as a class variable and initialized inside a test in JUnit

我正在JUnit设计测试用例。 我的问题是如何保存任何被声明为类变量并在测试中初始化的对象。 目前在这种情况下我得到java.lang.NullPointerException

以下是简要说明 - 我在下面列出了三项需要测试的服务 -

  1. 服务1(登录):它接受用户名密码对并返回cookie作为响应。
  2. 服务2(postmessage):它接受一条消息,该消息必须在请求中提供cookie并返回已发布消息的唯一ID
  3. 服务3(markasread) :它接受一个消息ID,必须提供cookie。 服务3中应返回应在服务3中使用的消息ID。

这是我期待的工作 -

import static org.junit.Assert.*;
import org.junit.Test;

public class ProfileTest{
    private String cookie;
    private String messageId;

    @Test
    public void loginTest(){
        String username = "demouser";
        String password = "demopassword";

        HttpResponse response = login(username, password);
        cookie = response.getCookie();

        assertEquals(response.getResponse(), "success");
    }

    @Test
    public void postmessageTest(){
        String message = "Hi, this is test message";
        HttpResponse response = postmessage(message, cookie);
        messageId = response.getCookie();

        assertEquals(response.getResponse(), "success");
    }

    @Test
    public void markasreadTest(){
        HttpResponse response = markasread(messageId, cookie);

        assertEquals(response.getResponse(), "success");
    }
}

答案是你不能,你不应该。 每次运行的测试用例都有自己的类变量副本。 这背后的想法只是每个测试用例应该独立运行,不应该相互依赖。

有可能通过一些垃圾代码,但我真的没有这样的建议。

如果可能的话,然后尝试将测试组合在一起并作为单个测试运行。

你不能这样做的原因是BlockJUnit4ClassRunner为每个叶子方法创建一个新的测试类实例。 它使用默认构造函数构造测试类。

BlockJUnit4ClassRunner

相关代码是

protected Object createTest() throws Exception {
    return getTestClass().getOnlyConstructor().newInstance();
}

暂无
暂无

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

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