[英]How to save any object which is declared as a class variable and initialized inside a test in JUnit
I am designing test cases in JUnit
. 我正在JUnit
设计测试用例。 My question is how to save any object which is declared as a class variable and initialized inside a test. 我的问题是如何保存任何被声明为类变量并在测试中初始化的对象。 Currently in such cases I am getting java.lang.NullPointerException
. 目前在这种情况下我得到java.lang.NullPointerException
。
Below is the brief description- I have three services listed below which needs to be tested- 以下是简要说明 - 我在下面列出了三项需要测试的服务 -
This is what I was expecting to work- 这是我期待的工作 -
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");
}
}
The answer is you cannot and you should not it. 答案是你不能,你不应该。 Each run of test cases will have its own copy of class variables. 每次运行的测试用例都有自己的类变量副本。 The idea behind this is just that each test case should run independently and should not depend on each other. 这背后的想法只是每个测试用例应该独立运行,不应该相互依赖。
It may be possible through some junk code but I really don't have such a recommendation for you. 有可能通过一些垃圾代码,但我真的没有这样的建议。
If possible then try to club the tescases together and run as a single one. 如果可能的话,然后尝试将测试组合在一起并作为单个测试运行。
The reason you can't do it is the BlockJUnit4ClassRunner creates a new instance of the test class per leaf method. 你不能这样做的原因是BlockJUnit4ClassRunner为每个叶子方法创建一个新的测试类实例。 It constructs the test class with the default constructor. 它使用默认构造函数构造测试类。
BlockJUnit4ClassRunner BlockJUnit4ClassRunner
The relevant code is 相关代码是
protected Object createTest() throws Exception {
return getTestClass().getOnlyConstructor().newInstance();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.