Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a good way to engage the initialization of a test suite when running an individual test case?

Under JUnit4, I have a test suite which uses a @classrule annotation to bootstrap a framework. This is needed to be able to construct certain objects during tests. It also loads some arbitrary application properties into a static. These are usually specific to the current test suite and are to be used by numerous tests throughout the suite. My test suite would look something like this (where FrameworkResource extends ExternalResource and does a lot of bootstrap work):

@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 really well and the main build has no problem executing all testsuites and their respective test cases (SuiteClasses?). The issue is when I'm in eclipse and I want to run just one test case individually withough having to run the entire suite (as part of the local development process). I would right click the java file Run As > JUnit Test and any test needing the framework resource or test properties would fail.

My question is this:

  1. Does JUnit4 provide a solution for this problem (without duplicating the initialization code in every test case)? Can a Test Case say something like @dependsOn(MyTestSuite.class)?.
  2. If Junit doesn't have a magic solution, is there a common design pattern that can help me here?
like image 353
icyitscold Avatar asked Nov 09 '22 23:11

icyitscold


1 Answers

As you are running just one test class, a good solution would be to move the initialisation code to the test class. You would need to add the @Before annotation to initialise the properties.

That would require that you duplicate the code on all your tests classes. For resolving this, you could create an abstract parent class that has the @Before method so all the child classes have the same initialization.

Also, the initialised data could be on static variables for checking if it is already initialised for that particular execution.

like image 124
jordiburgos Avatar answered Nov 14 '22 22:11

jordiburgos