Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit parameterized- create one instance for each parameter

I was annoyed to find in the Parameterized documentation that "when running a parameterized test class, instances are created for the cross-product of the test methods and the test data elements." This means that the constructor is run once for every single test, instead of before running all of the tests. I have an expensive operation (1-5 seconds) that I put in the constructor, and now the operation is repeated way too many times, slowing the whole test suite needlessly. The operation is only needed once to set the state for all of the tests. How can I run several tests with one instance of a parameterized test?

like image 928
Nate Glenn Avatar asked Jan 20 '13 21:01

Nate Glenn


1 Answers

I would move the expensive operation to a @BeforeClass method, which should execute just once for the entire parameterized test.

A silly example is shown below:

@RunWith(Parameterized.class)
public class QuickTest {

  private static Object expensiveObject;  
  private final int value;

  @BeforeClass
  public static void before() {
    System.out.println("Before class!");
    expensiveObject = new String("Just joking!");
  }


  @Parameters
  public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] { { 1 }, { 2 } });
  }      

  public QuickTest(int value) {
    this.value = value;
  }

  @Test
  public void test() {
    System.out.println(String.format("Ran test #%d.", value));
    System.out.println(expensiveObject);
  }
}

Will print:

Before class!
Ran test #1.
Just joking!
Ran test #2.
Just joking!
like image 110
Duncan Jones Avatar answered Sep 29 '22 15:09

Duncan Jones