Home > database >  Unit Test in Spring Boot for multiple values of property
Unit Test in Spring Boot for multiple values of property

Time:01-19

I'm having a Spring Boot application that defines a property application.mode inside my property file. The value of this property can be either SINGLE or MULTI.

src/main/resources/application.properties

application.mode=SINGLE

# also possible
#application.mode=MULTI

Some beans and bonfigs are loaded depending on the value of this property.

src/main/java/com.example.SomeService.java

@Bean
@ConditionalOnExpression("'${application.mode}'.equalsIgnoreCase(\"SINGLE\")")
public class SomeService {
   // some code
}

I also have a @SpringBootTest to check if the context loads and all beans are configured correctly.

src/test/java/com.example.SpringBootApplicationTest.java

@SpringBootTest
public class SpringBootApplicationTest {

    @Test
    public void contextLoads() {
    }
}

Currently I copied the application.properties file to src/test/resources folder. I manually start the unit test twice and edit the application.mode value in between to check if the Spring context loads with both values.

Is there a way to run this unit-test twice automatically and inject a different application.mode value for each run?

CodePudding user response:

You can override certain properties (even without properties file in src/test/resources) like so:

@SpringBootTest(properties = { "application.mode=SINGLE" })
class Whatevertest {
    ...
}

I'm not sure that you can test both cases in 1 test class, but creating 2 test classes should do the trick

  •  Tags:  
  • Related