spring-boot - @Value lateinit var 仅在从测试调用时才被实例化
问题描述
我在测试时无法使用我的 application.properties 值。
这是我的代码:
@Repository
class RedisSubscriptionStore(): SubscriptionStore {
@Value("\${default.package}")
lateinit var defaultPackageForFCMInstance: String }
这按预期工作。它在我的 updateSubscription 方法中使用,具有来自 application.properties 的正确值
问题出在我的测试中,当我使用该类时,该值未实例化并引发错误
@SpringBootTest()
@Tag("integration")
internal class RedisSubscriptionStoreIntegTest @Autowired constructor(
val objectMapper: ObjectMapper,
val redisTemplate: RedisTemplate<String, String>
) {
val sut = RedisSubscriptionStore(redisTemplate, objectMapper)
@Test
fun `return 200 when updating subscription`() {
sut.updateSubscription(updatedSub)
//Assert
val newlyUpdatedSub = getSubscription(updatedSub.peerID)
Assertions.assertEquals(updatedSub, newlyUpdatedSub)
}
但这会引发错误:lateinit 属性 defaultPackageForFCMInstance 尚未初始化
即使这适用于正确的值:
@SpringBootTest()
@Tag("integration")
internal class RedisSubscriptionStoreIntegTest @Autowired constructor(
val objectMapper: ObjectMapper,
val redisTemplate: RedisTemplate<String, String>
) {
@Value("\${default.package}")
lateinit var defaultPackageForFCMInstance: String
}
那么为什么从我的测试类调用时我的 defaultPackageForFCMInstance 没有初始化?它显然有一个值,我已经尝试在测试类中打印出来,然后再从 sut 调用它
解决方案
你正在实例化RedisSubscriptionStore
所以Spring没有办法注入价值。要么在构造函数中传递值,要么在测试中使用注入
@Autowired
var sut: RedisSubscriptionStore
推荐阅读
- django - 返回空字符串的模型方法
- python - 如何用win-32安装python 2.7.13??使用anaconda jupyter-notebook,创建新环境
- javascript - 如何使用 babel 预处理 .js 文件注释(在编译时)?
- html - 当水平卡列不同大小时使Bootstrap网格卡等高
- wordpress - 如何将本地构建的 wordpress(.org) 网站部署/托管到使用 siteground 购买的域
- javascript - 如何使用 JavaScript 在文本区域中执行退格?
- javascript - 为什么我的 Vis.js 力有向图不在 bootstrap 手风琴的视图中?
- audio - ffmpeg 水平翻转视频
- powerbi - 在 Power BI 中嵌入代码以发布到 Web(公共)时报告未加载
- google-sheets - Google表格,根据包含公式的单元格值添加行