Vinod Jeeru
Vinod Jeeru

Reputation: 11

How to implement common data sharing between individual JUnit Testcases

I have three test cases namely Test1.java, Test2.java, Test3.java. In every testcase i am interacting with one file about to read the data. Which means i am reading the file data in @BeforeClass of every testcase and unloading the same data in @AfterClass of every testcase.

So now my requirement is that, i wanted to do file read operation before executing the those 3 testcases and the same data should be able to share among those 3 testcases while executing them.

Currently i have implemented below:

public class Test1{
private File testFile;
    @BeforeClass
    public static void setUpFiledata() {
        // Code for reading the file data
    }
    @AfterClass
    public static void tearDownFiledata() {
        // Code for unloading the file data
    }
}

public class Test2{
private File testFile;
    @BeforeClass
    public static void setUpFiledata() {
        // Code for reading the file data
    }
    @AfterClass
    public static void tearDownFiledata() {
        // Code for unloading the file data
    }
}

public class Test3{
private File testFile;
    @BeforeClass
    public static void setUpFiledata() {
        // Code for reading the file data
    }
    @AfterClass
    public static void tearDownFiledata() {
        // Code for unloading the file data
    }
}

In the above code, every testcase has a @BeforeClass & @AfterClass methods to initialize the file which is common for every testcase. Now i require a way which can share the file content in every testcase.

Upvotes: 1

Views: 53

Answers (1)

Mebin Joe
Mebin Joe

Reputation: 2209

You can use test suite to run these tests, and use @BeforeClass and @AfterClass on the test suite:

@RunWith(Suite.class)
@Suite.SuiteClasses({Test1.class, Test2.class, Test3.class})
public class MySuite {
    @BeforeClass
    public static void setUpFiledata() {
        // Code for reading the file data
    }
    @AfterClass
    public static void tearDownFiledata() {
        // Code for unloading the file data
    }
}

Upvotes: 1

Related Questions