When implementing E2E tests using JUnit in the test runner, I divided the test class for each screen and API. At this time, I considered how to define a test method that is common to multiple test classes.
By defining a common test method in the parent class of the test class, the test method of the parent class is also executed when each test class is executed.
The behavior peculiar to each test class is defined as an interface (or an abstract method of the parent class), and the common test method uses this interface to implement the test.
public abstract class CommonTestA {
//Abstract methods for defining behaviors specific to test classes
abstract SomeObject doSomething();
@Test
public void commonTestX() {
// doSomething()Implement common test cases using
}
}
//CommonTest when running this test class.commonTestX()Is also executed
public class TestClass extends CommonTestA {
//Implement test cases specific to the test class
}
With this method, one test class can inherit only one common test class due to Java inheritance restrictions, which is a problem when you want to create multiple common test classes.
You can avoid the problem (1) by using the default method of the interface introduced in Java 8. (Because multiple interfaces can be implemented in one class.) However, in JUnit 4 and earlier, the default method is not executed in the implementation class, so you need to use JUnit 5.
public interface CommonTestA {
SomeObject doSomething();
@Test
default void commonTestA() {
//Define a common test method as the default method
}
}
//You can implement multiple common test interfaces in one test class
public class TestClassX implements CommonTestA, ComonTestB {
// ...
}
Recommended Posts