Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define variable before all JUnit Tests start running?

Tags:

java

junit

I have some code that I want to run before all @Tests in a Junit file. This code will call a TCPServer, get some data, convert it into a usable format (i.e., string) and THEN I want tests to run on top of that. I can call the server in each test, but after two tests the server stops responding. How would I do something like that? This is essentially what I have so far:

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
    }
}

I tried using @BeforeClass, but the terser didn't remain in scope. I am very much a Java newbie, so any help would be appreciated! Thanks!

like image 407
kroe761 Avatar asked Dec 12 '25 14:12

kroe761


1 Answers

You need to make your Terser a field of your class, as follows:

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
    }
}

In this setup, getData is run only once before all of your tests, and it intializes your Terser pcd01 as specified. You can then use pcd01 in each test as the scope of fields make them available to all methods in the class.

like image 75
heenenee Avatar answered Dec 15 '25 09:12

heenenee