@DynamicPropertySource
@DynamicPropertySource
是一个注释,可以应用于需要在集成测试类中注册 dynamic 属性以添加到 ApplicationContext
的 PropertySources
中的方法,后者是为集成测试加载的。当您不了解属性值时,动态属性非常有用 - 例如,如果属性是由外部资源(例如由 Testcontainers 项目管理的容器)管理的。
@DynamicPropertySource
is an annotation that can be applied to methods in integration
test classes that need to register dynamic properties to be added to the set of
PropertySources
in the Environment
for an ApplicationContext
loaded for an
integration test. Dynamic properties are useful when you do not know the value of the
properties upfront – for example, if the properties are managed by an external resource
such as for a container managed by the Testcontainers project.
以下示例演示如何注册动态属性:
The following example demonstrates how to register a dynamic property:
- Java
-
@ContextConfiguration class MyIntegrationTests { static MyExternalServer server = // ... @DynamicPropertySource (1) static void dynamicProperties(DynamicPropertyRegistry registry) { (2) registry.add("server.port", server::getPort); (3) } // tests ... }
1 | Annotate a static method with @DynamicPropertySource . |
2 | Accept a DynamicPropertyRegistry as an argument. |
3 | Register a dynamic server.port property to be retrieved lazily from the server.
|
4 | Annotate a static method with @DynamicPropertySource . |
5 | Accept a DynamicPropertyRegistry as an argument. |
6 | Register a dynamic server.port property to be retrieved lazily from the server. |
有关进一步的详细信息,请参见 Context Configuration with Dynamic Property Sources 。
See Context Configuration with Dynamic Property Sources for further details.