javaspring-boot

Override a single property for all tests


I have a set of properties in src/main/resources/application.properties:

app.firstprop=2
app.secondprop=3
app.thirdprop=5
app.fourthprop=7

And I want to override app.secondprop for all my tests, while keeping the remaining properties unchanged. One option is:

@SpringBootTest(properties=["app.secondprop=99"])

but that means I have to repeat this property value in every single test file.

Another option is to use src/test/resources/application.properties to override my properties file. Unfortunately, I have to specify all the unchanged properties as well as the overridden property:

app.firstprop=2
app.secondprop=99
app.thirdprop=5
app.fourthprop=7

If I don't specify the unchanged properties, they won't be defined during the tests. This again is unwanted repetition.

How do I override a single property for all tests and keep to the DRY principle?


Solution

  • If you want a specific property value in all your tests, then follow Andrew S's suggestion:

    If you want a specific property value in some tests, then use test class inheritance:

    @SpringBootTest(properties = {"app.secondprop=99"})
    interface ParentTest {
    }
    
    class ChildTest implements ParentTest {
    
        @Value("${app.secondprop}")
        private String prop2nd;
    
        @Test
        void test() {
            assertEquals("99", prop2nd);
        }
    }
    
    // here you implement ParentTest, but overrides the prop's value
    @SpringBootTest(properties = {"app.secondprop=199"})
    class ChildTestWithOwnValue implements ParentTest {
    
        @Value("${app.secondprop}")
        private String prop2nd;
    
        @Test
        void test() {
            assertEquals("199", prop2nd);
        }
    }