简体   繁体   中英

Setup system properties and statics just once before running all test classes in java

I have multiple java test classes that extend a common base class. Currently I have two methods - startUp() and shutDown() with @BeforeClass and @AfterClass annotations respectively which make these methods run once before and after each test class.

I want to define a member in the base class which can be shared by all test classes (so will have to make it static). This class member requires some system properties to be set before it can be initialized.

Is there a say to set these system properties just once before all tests (in all test classes combined) and then set the static member?

I do not want to use junit Suites as I may add more test classes later and that will result in making changes to Suites every time causing an additional dependency.

You can try JUnit rules like this:

@Rule
public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();

@BeforeClass
public static void beforeClass() {
    System.setProperty("MY_PROPERTY", "myNewValue");
}   

the rule thing will take care of the rest and recreate the property when needed, you just need a new test dependency:

<dependency>
    <groupId>com.github.stefanbirkner</groupId>
    <artifactId>system-rules</artifactId>
    <version>1.2.0</version>
    <scope>test</scope>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM