簡體   English   中英

為 kotlin 中的單元測試分配“val”

[英]assign "val" for unit test in kotlin

我正在 kotlin 中編寫單元測試,為此我需要為“val”賦值,這里是代碼的簡化版本:

@Entity
@Table(name = "Request")
data class Request(

    @Column(name = "Name")
    val name: String,
) {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    var id: Long? = null

    @CreationTimestamp
    @Column(name = "Created")
    val created: LocalDateTime = LocalDateTime.now()
}

@Test
fun `test one`() {
    val name = RandomStringUtils.randomNumeric(10)
    val id = Random.nextLong(100)
    val created = LocalDateTime.now().minusHours(48)
    
    val request = Request(playerUid = playerUid).apply {
        id = id
        created = created
    }
}

在測試中分配“創建”時出現編譯錯誤。 我應該如何管理這個單元測試,因為我需要設置我想要的“創造”值? (我不能觸摸“請求類”的任何部分)

如果您無法更改Request class 的任何部分,那么您將無法更改created

您將需要通過使用近似測試范圍來測試createdcreated需要 0<now<2s 之類的東西)

將 static 訪問器編碼為LocalDateTime.now()之類的函數是一個設計缺陷 - 這應該在服務 class 的外部設置。如果你真的做不到,那么這是另一種 hacky 方法:

  1. 在某處添加 CLOCK object (不需要在伴隨對象中)但最終你必須更改created的分配:
@Entity
@Table(name = "Request")
data class Request(
    @Column(name = "Name")
    val name: String,
) {
    companion object {
        /** used for carrying a Clock only in the case of tests **/
        val CLOCK = ThreadLocal<Clock>()
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    var id: Long? = null

    @CreationTimestamp
    @Column(name = "Created")
    val created: LocalDateTime = LocalDateTime.now(CLOCK.get() ?: Clock.systemUTC())
}

通常你不會碰那個CLOCK但在單元測試中你定義了一個

private val fixedClock = Clock.fixed(Instant.parse("2022-08-29T08:20:50Z"), ZoneOffset.UTC)

那么你需要

@BeforeEach
fun beforeEach() {
    // this is necessary because the serialization of MemberMentorCommon.weeksOnPlan uses a clock
    CLOCK.getOrSet { fixedClock }
}

@AfterEach
fun afterEach() {
    CLOCK.remove()
}

是的,ThreadLocals 很討厭,但這允許您更改 Request class 的行為以覆蓋now() function

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM