在所有JUnit测试开始运行之前定义变量



我有一些代码要在Junit文件中的所有@Test之前运行。这段代码将调用TCPServer,获取一些数据,将其转换为可用的格式(即字符串),然后我希望在此基础上运行测试。我可以在每次测试中调用服务器,但在两次测试后,服务器停止响应。我该怎么做这样的事?这基本上就是我到目前为止所拥有的:

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新手,所以任何帮助都将不胜感激!谢谢

您需要使Terser成为类的字段,如下所示:

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,因为字段的作用域使它们可用于类中的所有方法。

最新更新