![](/img/trans.png)
[英]How to instantiate my Interface object inside Junit test class?
[英]How to save any object which is declared as a class variable and initialized inside a test in JUnit
我正在JUnit
设计测试用例。 我的问题是如何保存任何被声明为类变量并在测试中初始化的对象。 目前在这种情况下我得到java.lang.NullPointerException
。
以下是简要说明 - 我在下面列出了三项需要测试的服务 -
这是我期待的工作 -
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为每个叶子方法创建一个新的测试类实例。 它使用默认构造函数构造测试类。
相关代码是
protected Object createTest() throws Exception {
return getTestClass().getOnlyConstructor().newInstance();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.