将 id 注入 JPA 实体以进行单元测试

问题描述 投票:0回答:1

使用 Spring Boot 3 JPA (Kotlin),我有一个带有自动生成的 id 属性的实体。现在我有了将这样的实体转换为 DTO 的代码(并且 id 在这种情况下很重要)。如何将 id 注入实体以对该代码进行单元测试? (我不想对数据库使用重量级测试)。构造函数不允许传递 id,我不想更改生产代码。

@Entity
@Table(name = "users")
data class User(
@Column(name = "created_at", nullable = false)
    val createdAt: Instant,
){
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    var id: Int = 0
}
kotlin unit-testing jpa spring-data-jpa auto-increment
1个回答
0
投票

我的情况有所不同,但你应该能够从这种方法中得到启发。

  • 我正在使用 Mongo,但仍然使用 Spring Data / JPA
  • 在我的例子中,我们在客户端而不是服务器上生成 id,但您仍然可以拦截实体并设置 Id
  • 我正在使用 MockK,一个 Kotlin 模拟库。 你没有说你正在使用什么,但同样可以将原理转移到 Mockito 等。

实例化测试类时,以下函数创建一个模拟

Respository
,出于我的目的,它只是将实体存储在
MutableMap
中,仅模拟另一个函数,即
findById(..)

private val savedAppointmentsById = mutableMapOf<RULID, MemberAppointment>()

private fun createSemiStatefulAppointmentRepositoryMock(): AppointmentRepository {
    val repository: AppointmentRepository = mockk(relaxed = false)
    savedAppointmentsById.clear()

    every { repository.save(any()) } answers {
        val appointment = firstArg<MemberAppointment>()
        // here you would do something like appointment.id = <new id>
        savedAppointmentsById.put(appointment.id, appointment)
        appointment
    }

    every { repository.findById(any()) } answers {
        Optional.ofNullable(savedAppointmentsById.get(firstArg<RULID>()))
    }
    return repository
}
© www.soinside.com 2019 - 2024. All rights reserved.