Search code examples
javajunitjunit4

iterative testing using junit


I have a bunch of test inputs that I would like to run and compare the output with expected:

@Test
void test () throws IOExeption {
  for (File i : readDir()) {
    File out = foo(i);
    assertEquals(FileUtils.readLines(expected), FileUtils.readLines(out));
  }
}

I would like to run the tests using JUnit. But if I do it like the above then JUnit will stop after encountering the first test failure. Is there a better way to do this other than making each file its own test case like below?

@Test
void test1 () throws IOExeption {
  File i = readFile("1.txt");
  File out = foo(i);
  assertEquals(FileUtils.readLines(expected), FileUtils.readLines(out));      
}

@Test
void test2 () throws IOExeption {
  File i = readFile("2.txt");
  File out = foo(i);
  assertEquals(FileUtils.readLines(expected), FileUtils.readLines(out));      
}

Solution

  • I think, that you could use Parameterized. This is standard feature of JUnit. Below you can see an example.

    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    
    import java.util.Arrays;
    import java.util.Collection;
    
    @RunWith(Parameterized.class)
    public class Foo {
        @Parameterized.Parameters
        public static Collection<Object[]> data() {
            return Arrays.asList(new Object[][] { { "1.txt" }, { "2.txt" } });
        }
    
        @Parameterized.Parameter // first data value (0) is default
        public /* NOT private */ String fileName;
    
        @Test
        public void test() {
            File i = readFile(fileName);
            File out = foo(i);
            assertEquals(FileUtils.readLines(expected), FileUtils.readLines(out));
        }
    }
    

    I have not found JUnit official documentation about this, but you can find more details e.g. in this tutorial: https://www.tutorialspoint.com/junit/junit_parameterized_test.htm