Is there a good way to enable test suite initialization when running a separate test case?

In JUnit4, I have a test suite that uses the @classrule annotation to load a framework. This is necessary in order to be able to create specific objects during the tests. It also loads some arbitrary application properties into static ones. They are usually specific to the current test suite and should be used by numerous tests throughout the suite. My test suite will look something like this (where FrameworkResource extends ExternalResource and does a lot of loading):

 @RunWith(Suite.class) @SuiteClasses({com.example.test.MyTestCase.class}) public class MyTestSuite extends BaseTestSuite { @ClassRule public static FrameworkResource resource = new FrameworkResource(); @BeforeClass public static void setup(){ loadProperties("props/suite.properties") } } 

The above works very well, and in the main assembly there are no problems with all the tests and their corresponding test cases ( SuiteClasses ?). The problem is when I'm in an eclipse, and I want to run only one test case separately, without having to run the whole package (as part of the local development process). I would immediately click on the java file Run As> JUnit Test, and any test that requires resource resources or test properties will fail.

My question is:

  • Does JUnit4 provide a solution to this problem (without duplicating the initialization code in each test case)? Can a test case say something like @dependsOn(MyTestSuite.class) ?
  • If Junit doesn't have a magical solution, is there a generic design template that can help me here?
+5
source share
1 answer

Since you use only one test class, a good solution would be to translate the initialization code into a test class. You will need to add the @Before annotation to initialize the properties.

This will require code duplication in all of your test classes. To solve this issue, you can create an abstract parent class that has the @Before method, so all child classes have the same initialization.

In addition, the initialized data can be on static variables to check if it has already been initialized for this particular execution.

+1
source

Source: https://habr.com/ru/post/1206877/


All Articles