简体   繁体   中英

JUnit - parameterized test - multiple constructor calls

I have a list of text files. I can't load them all together, so I constructed a parameterized test, where only some of the files get tested together (test1: file1...file5, test2: file6...file10, ...). The files are loaded in the constructor of the class. The range of files loaded depends on the parameters. I have different test methods in the class (code for describe the problem below).

The problem: The constructor is called separately for every tested method of the class. That means: With 10 methods to test, the constructor is called 10 times for every range of files to test. Consequence: The files are loaded in every test case 10 times via the constructor call.

Any explanation or solution for that problem?

@RunWith(Parameterized.class)   
public class PageListTest {

    private int fileFrom, fileTo;

    @Parameters
    public static Collection<Object[]> data() {
        Object[][] data = new Object[][] {{0, 3}, {22, 24}};
        return Arrays.asList(data);
    }

    public PageListTest(int from, int to) throws Exception {
        fileFrom = from;
        fileTo = to;
        //files are loaded ....
    }

    @Test
    public void testA() {
        //....
    }

    @Test
    public void testB() {
        //....
    }

    //....
}

Thanks in advance.

PS: Of course I could solve the problem by calling all methods to test out of one 'as TEST' declared method. Bur I would like a better solution.

Explanation: that's how JUnit works. There's a new class instance for each test .

Create a static map of file number to file contents. In your constructor, test to see if you've already loaded the file. If not, load it. If yes, skip!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM