3

I've got a

thing=false 

In my property file for a Spring Boot project. While running my Junit tests for the project, I want

 thing=true

How do I do this?

adisplayname
  • 117
  • 1
  • 10

3 Answers3

1

Just add application.properties file in:

src -> test -> resources

and set property to desired value.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
  • Are there any ways to do this without changing a property file? I'd like to only use Java code in the Junit to change properties for my test – adisplayname Oct 30 '18 at 16:14
1

You can set a particular configuration property for your unit tests using the TestPropertySource annotation with the properties parameter:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
@TestPropertySource(properties = {
    "thing=true"
})
public class ThingTrueTests {

}

This provides a way to set a configuration property without using a properties/yaml file. However it is a class-level annotation so it will apply to all the tests in that class.

If you have a set of tests that rely on thing being false then put these in one unit test class and put all the tests that rely on thing being true in another unit test class.

Note: If you're writing groovy code then the TestPropertySource annotation would look like this:

@TestPropertySource(properties = [
    "thing=true"
])
Joman68
  • 2,248
  • 3
  • 34
  • 36
0

Spring provides a support for the same use @TestPropertySource annotation , is a class-level annotation that is used to configure the locations() of properties files and inlined properties() to be added to the Environment's set of PropertySources for an ApplicationContext for integration tests.

Example

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AppConfig.class)
@TestPropertySource(locations="classpath:test.properties")
public class SampleApplicationTests {

}

in your test.properties present in Junit class path you can override the variable you want mentioned under application.properties

Amit Kumar Lal
  • 5,537
  • 3
  • 19
  • 37