how can I reuse JUnit tests in another testclass?
For example:
public TestClass1 {
@Test
public void testSomething(){...}
}
public TestClass
Avoid the scenario, in general. It is prone to making tests much more brittle. If TestClass1
fails, then TestClass2
implicitly fails, which isn't desirable for at least the following reasons:
Occasionally sharing sections of test code is useful, particularly for integration tests. Here's how you might do it without depending on the tests themselves:
public abstract BaseTests {
protected void somethingHelper() {
// Test something
}
}
public TestClass1 extends BaseTests {
@Test
public void testSomething(){
somethingHelper();
}
}
public TestClass2 extends BaseTests {
@Test
public void testSomethingAndSomethingElse() {
somethingHelper();
// and then test something else
}
}
Alternatively, you could use a helper class and avoid the inheritance altogether. Asserts and the like can go in the somethingHelper()
method.
Don't call a method from TestClass1
in TestClass2
directly. The test cases become less readable this way, and can lead to spaghetti frittata.