'How to override properties by each test in unitTest

I have the next configuration in my unit Test:

@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@TestPropertySource(locations="classpath:itest.properties", properties = "server.username = inlined")

public class IqClientImplTest

With this configuration on my test class, I'm changing the server.username property from the one defined in the .properties file to inlined But I need to do this at the test level, because I need to override this property value with different values by each test, for example in one could be empty and in another one I need the admin value.

Do you know how can I override the .properties value at the test level and not at the class level?

Thanks!



Solution 1:[1]

You can inject Environment class inside your test class. Then you can try customize environment properties.

eg: https://stackoverflow.com/a/35769953/1811348

Here you will not change anything in postconstruct, but in your own test method where you want to override settings.

and to reset you can add DirtiesContext annotation to the test method.

ref: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

Other way is to set system property in each test method with:

System.setProperty("simple_test_env_property","somevalue");

also ensure you add dirtiescontext. Maybe dirtiescontext is overkill and not required but you can checkout.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 swapyonubuntu