Java 在所有JUnit测试开始运行之前定义变量?
我想在Junit文件中的所有@Tests之前运行一些代码。这段代码将调用一个TCPServer,获取一些数据,将其转换为一种可用的格式(即字符串),然后我希望在该格式上运行测试。我可以在每次测试中调用服务器,但在两次测试后,服务器停止响应。我该怎么做那样的事?这基本上就是我到目前为止所做的:Java 在所有JUnit测试开始运行之前定义变量?,java,junit,Java,Junit,我想在Junit文件中的所有@Tests之前运行一些代码。这段代码将调用一个TCPServer,获取一些数据,将其转换为一种可用的格式(即字符串),然后我希望在该格式上运行测试。我可以在每次测试中调用服务器,但在两次测试后,服务器停止响应。我该怎么做那样的事?这基本上就是我到目前为止所做的: public class Test { public Terser getData() throws Exception { // Make the connection to PM
public class Test {
public Terser getData() throws Exception {
// Make the connection to PM.service
TCPServer tc = new TCPServer();
String [] values = tc.returnData();
// Make the terser and return it.
HapiContext context = new DefaultHapiContext();
Parser p = context.getGenericParser();
Message hapiMsg = p.parse(data);
Terser terser = new Terser(hapiMsg);
return terser;
}
@Test
public void test_1() throws Exception {
Terser pcd01 = getData();
// Do Stuff
}
@Test
public void test_2() throws Exception {
Terser pcd01 = getData();
// Do Stuff
}
@Test
public void test_3() throws Exception {
Terser pcd01 = getData();
// Do stuff
}
}
我试着使用@BeforeClass,但简练的内容不在范围之内。我是一个Java新手,所以任何帮助都将不胜感激!谢谢 您需要使您的
更简洁
成为类的字段,如下所示:
public class Test {
static Terser pcd01 = null;
@BeforeClass
public static void getData() throws Exception {
// Make the connection to PM.service
TCPServer tc = new TCPServer();
String [] values = tc.returnData();
// Make the terser and return it.
HapiContext context = new DefaultHapiContext();
Parser p = context.getGenericParser();
Message hapiMsg = p.parse(data);
pcd01 = new Terser(hapiMsg);
}
@Test
public void test_1() throws Exception {
// Do stuff with pcd01
}
@Test
public void test_2() throws Exception {
// Do stuff with pcd01
}
@Test
public void test_3() throws Exception {
// Do stuff with pcd01
}
}
在此设置中,
getData
在所有测试之前只运行一次,并按照指定初始化Terser pcd01
。然后,您可以在每个测试中使用pcd01
,因为字段的作用域使它们对类中的所有方法都可用。请编辑您的问题,以包括您尝试的@BeforeClass版本。这不会编译@BeforeClass
必须位于静态方法上<代码>pcd01也必须是静态的。谢谢!工作得很有魅力!