实体类时间戳精度与数据库字段精度不一致导致的测试用例失败
在编写简单的单元测试过程中存在这样一个问题:
- 将实体类存入数据库,此时为 t1
- 将实体类从数据库取出,此时为 t2
- 断言 t1 与 t2 完全相等
上面可能出现问题,如果实体类的时间戳精度大于数据库中存储的时间戳精度会导致取出的时间在丢失精度的部分不一致,比如:
@Entity
class User(
@Id
@GeneratedValue(strategy = GenerationType.UUID)
val id: String? = null,
var username: String,
var password: String,
@CreationTimestamp val createdAt: Instant? = null,
@UpdateTimestamp val updatedAt: Instant? = null,
)
interface UserRepository : JpaRepository<User, String>
@DataJpaTest
class UserRepositoryTest(@Autowired private val userRepository: UserRepository) {
@Test
fun test() {
val user = userRepository.saveAndFlush(
User(
username = "test_user_1",
password = "test_user_1",
)
)
val userByFind = userRepository.findByIdOrNull(user.id!!)
// 这里不一定会断言通过,因为精度不一样所以两次取出来的时间戳字段
// createdAt 和 updatedAt 在丢失的精度上可能不一致
// 因为 Instant 在 java 中的精度达到了纳秒,但是对应到数据库 timestemap
// 却只精确到毫秒
assertThat(userByFind).isEqualTo(user)
}er
}