使用 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
}
我的情况有所不同,但你应该能够从这种方法中得到启发。
实例化测试类时,以下函数创建一个模拟
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
}