Creating a JUnit testsuite with multiple instances

2019-08-07 20:44发布

问题:

I want to create a TestSuite from multiple text files. Each textfile should be one Test and contains the parameters for that test. I have created a Test like:

@RunWith(Parameterized.class)
public class SimpleTest {
  private static String testId = "TestCase 1";
  private final String parameter;

  @BeforeClass
  public static void beforeClass() {
    System.out.println("Before class " + testId);
  }

  @AfterClass
  public static void afterClass() {
    System.out.println("After class " + testId);
  }

  @Before
  public void beforeTest() {
    System.out.println("Before test for " + testId + ":" + parameter);
  }

  @After
  public void afterTest() {
    System.out.println("After test for " + testId + ":" + parameter);
  }

  @Parameters
  public static Collection<String[]> getParameters() {
    //Normally, read text file here.
    return Lists.newArrayList(new String[] { "Testrun 1" }, new String[] { "Testrun 2" });
  }

  public SimpleTest(final String parameter) {
    this.parameter = parameter;
  }

  @Test
  public void simpleTest() {
    System.out.println("Simple test for " + testId + ":" + parameter);
  }

  @Test
  public void anotherSimpleTest() {
    System.out.println("Another simple test for " + testId + ":" + parameter);
  }
}

Now I want to create a Suite which runs this test multiple times. But because the Parameterized, BeforeClass and AfterClass all runs only once, this seems a bit impossible.

So, to sum it up:

  1. I want to run a Test multiple times.
  2. Each time I need an input parameter (Like the name of a textfile)
  3. Each time the BeforeClass, AfterClass and Parameters functions should be called
  4. I rather not make a subclass for each text file.

Is this possible?

回答1:

I think you can use @Before and @After, but they run before or after each test. If you can live with it, use them. If you need to execute that after all test methods, I don't think there's anything like that.

Could you perhaps simulate it by using some conditionals in an @After method?