@DynamicPropertySource

@DynamicPropertySource是一個註解,可應用於整合測試類中的方法,這些方法需要註冊動態屬性,以新增到為整合測試載入的ApplicationContextEnvironment中的PropertySources集合中。當您無法預先知道屬性值時,動態屬性非常有用——例如,如果屬性由外部資源(如由Testcontainers專案管理的容器)管理。

以下示例演示如何註冊動態屬性

  • Java

  • Kotlin

@ContextConfiguration
class MyIntegrationTests {

	static MyExternalServer server = // ...

	@DynamicPropertySource (1)
	static void dynamicProperties(DynamicPropertyRegistry registry) { (2)
		registry.add("server.port", server::getPort); (3)
	}

	// tests ...
}
1 使用@DynamicPropertySource註解一個static方法。
2 接受一個DynamicPropertyRegistry作為引數。
3 註冊一個動態的server.port屬性,該屬性將從伺服器延遲檢索。
@ContextConfiguration
class MyIntegrationTests {

	companion object {

		@JvmStatic
		val server: MyExternalServer = // ...

		@DynamicPropertySource (1)
		@JvmStatic
		fun dynamicProperties(registry: DynamicPropertyRegistry) { (2)
			registry.add("server.port", server::getPort) (3)
		}
	}

	// tests ...
}
1 使用@DynamicPropertySource註解一個static方法。
2 接受一個DynamicPropertyRegistry作為引數。
3 註冊一個動態的server.port屬性,該屬性將從伺服器延遲檢索。

有關詳細資訊,請參見使用動態屬性源進行上下文配置

© . This site is unofficial and not affiliated with VMware.