tk2000 tk2000 - 5 months ago 34
Java Question

How to reuse existing JUnit tests in another test class?

how can I reuse JUnit tests in another testclass?

For example:

public TestClass1 {
@Test
public void testSomething(){...}
}

public TestClass2 {
@Test
public void testSomethingAndSomethingElse() {
// Somehow execute testSomething()
// and then test something else
}
}

Answer

As usual you can:

  1. Extends TestClass2 from TestClass1
  2. Access TestClass1 from TestClass2 using delegation:

Example 1:

// Instantiate TestClass1 inside test method
public TestClass2 {
    public void testSomethingAndSomethingElse1() {
         new TestClass1().testSomething();
    }
}

Example 2:

// Instantiate TestClass1 as a member of TestClass2
public TestClass2 {
    private TestClass1 one = new TestClass1();
    public void testSomethingAndSomethingElse1() {
         one.testSomething();
    }
}