Properly set (system) properties in JUnit 5

后端 未结 3 846

We are using an approach similar to System Rules to handle (system) properties in our JUnit 4 tests. The main reason for this is to clean up the environment after each test,

3条回答
  •  心在旅途
    2021-01-12 00:51

    The JUnit Pioneer way requires the system properties to be known at compile time. Where they are generated at runtime, say via Testcontainers or Wiremock creating things on random ports, it may be better to use something which can be driven from dynamic values.

    The problem can be solved with System Stubs https://github.com/webcompere/system-stubs which provides JUnit 5 and is a fork of the code from System Lambda, itself built by the author of System Rules.

    @ExtendWith(SystemStubsExtension.class)
    class SomeTest {
        // can be initialised here with some up front properties
        // or leave like this for auto initialization
        @SystemStub
        private SystemProperties someProperties;
    
        @BeforeEach
        void beforeEach() {
            someProperties.set("prop1", "value1")
                .set("prop2", "value2");
        }
    
        @Test
        void someTest() {
            // properties are set here
            // and can also call System.setProperty
    
    
            // properties reset to state before the test case ran
            // as the test case is tidied up
        }
    }
    
    

提交回复
热议问题