Best way to initialize objects which can be used by all junit test cases

Shruti Seth :

I'm not sure if a question similar to this already exists but i was not able to find any helpful answers.

I have to create a list of objects that are supposed to be used by all the junit test cases.

If i write a @BeforeClass method like this:

 @BeforeClass
 static public void setUp() {
    MyObject object = new MyObject (int a, Stringb)
 }

It does n't work because these objects are out of scope for the junit test cases

And if i write @BeforeClass method like this:

Class Abc{
    MyObject object; 
    @BeforeClass
     static public void setUp() {
        object = new MyObject (int a, Stringb)
     }
}

There's a compilation error as i can't access non static variable from static class.

I could make all the objects static but that seems unnecessary to me. What is the best way to do this?

Michael :

I recommend using @Before for your use case:

class Abc {

    MyObject object; 

    @Before
    public void setUp() {

        object = new MyObject();
    }

    @Test
    public void test() {
        // Use object
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=131750&siteId=1