User1
User1

Reputation: 41271

How to instantiate a shared resource in JUnit

I noticed that jUnit runs the constructor of my test class for each method being tested. Here's an example:


public class TestTest {
    protected BigUglyResource bur;
    public TestTest(){
        bur=new BigUglyResource();
        System.out.println("TestTest()");
    }
    @Test
    public void test1(){
        System.out.printf("test1()\n");
    }

    @Test
    public void test2(){
        System.out.printf("test2()\n");
    }
    @Test
    public void test3(){
        System.out.printf("test3()\n");
    }
}

Gives the following result:

TestTest()
test1()
TestTest()
test2()
TestTest()
test3()

Calling the constructor to BigUglyResource is too time-consuming, I'd prefer to build it only once. I know you can use @BeforeClass to run a method once, but @BeforeClass is only for static methods. Static methods can't access a class property like BigUglyResource in the example above. Other than building a Singleton, what options are there?

Upvotes: 3

Views: 1799

Answers (3)

akoz
akoz

Reputation: 401

For JUnit5 users: you have to use @BeforeAll annotation instead of @BeforeEach, the rest stays the same as in bruno's and Russ'es answers.

private static BigUglyResource bur;

@BeforeAll
public static void before(){
   bur=new BigUglyResource();
}

Upvotes: 0

bruno conde
bruno conde

Reputation: 48255

Can't you declare the BigUglyResource static? This is how I normally do it.

private static BigUglyResource bur;

@BeforeClass
public static void before(){
   bur=new BigUglyResource();
}

Upvotes: 6

Russ Hayward
Russ Hayward

Reputation: 5677

You could make "bur" static:

protected static BigUglyResource bur;

And use @BeforeClass.

Upvotes: 1

Related Questions