如何通过unitTest中的每个测试覆盖属性
我的单元测试中有下一个配置:
@SpringBootTest(webEnvironment = WebEnvironment.NONE)
@TestPropertySource(locations="classpath:itest.properties", properties = "server.username = inlined")
public class IqClientImplTest
在测试类中使用此配置,我将从.properties File中定义的server.username
属性更改为ninlined ,但我需要在测试级别上执行此操作,因为我需要用每个测试用不同的值覆盖此属性值,例如,一个可能是空的,而在另一个测试中,我需要管理员值。
您知道如何在测试级别而不是在班级级别上覆盖。
谢谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
There is a very simple pattern that I use based on the
要记住的关键是要确保测试恢复其被突变为在结束测试之前突变之前的同一状态。否则,这可能会成为很难追踪的错误的来源。
There is a very simple pattern that I use based on the ReflectionTestUtils class as of Spring Boot 2.5.
The key thing to remember is to ensure the test restores whatever it is being mutated to the same state it was before the mutation prior to ending the test. Otherwise, this can become the source of bugs that are very difficult to track down.
您可以在测试类中注入环境类。然后您可以尝试自定义环境属性。
例如:
https://stackoverflow.com/a/35769953/1811348
在这里,您不会在 postconstruct 中更改任何内容,而是在您自己的中更改您想要覆盖设置的测试方法。
要重置,您可以将 DirtiesContext 注释添加到测试方法中。
参考: https: //docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html
另一种方法是在每个测试方法中设置系统属性:
也确保添加 dirtycontext。也许 dirtycontext 太过分了,不是必需的,但你可以结账。
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:
also ensure you add dirtiescontext. Maybe dirtiescontext is overkill and not required but you can checkout.