2

I want to test my code with "real" data. This data can be reused in every test in the suite since is read only data.

The loading of the data is lengthy and I would like to reuse the loaded data all through the suite (in numerous test cases). Right now I store the data as a static field. Something like this:

Context.setData(new DataReader().getData(url));

What would be a more "JUnit" way of doing this (i.e loading a big bulk of data and use it in several test cases)? I really don't like this as it has evident drawbacks. For example, who initializes the data?

What other options do I have to achieve this?

El Marce
  • 3,144
  • 1
  • 26
  • 40

1 Answers1

1

You might want to use ParametrizedTests:

import java.net.URL;
import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class MyTest {

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                 { new DataReader().getData(url) }
           });
    }

    private final Data data;

    public MyTest( Data data) {
        this.data = data;
    }

    @Test
    public void test1() {
        //
    }

    @Test
    public void test2() {
        //
    }
}

The method annotated @Parameters is invoked only once.

gontard
  • 28,720
  • 11
  • 94
  • 117
  • Thank U @gontard, but this does not what I want. This seems to test the same logic with different data. I want to do it the other way around, to test different logics with one single set of data. Thanks – El Marce Jul 18 '14 at 13:43
  • Yes, it is not the purpose of `Parameterized` test. But it fit your example, by providing the same parameter to all your tests. – gontard Jul 23 '14 at 08:30