【问题标题】:Unit test is not passing because of LocaDateTime field由于 LocaDateTime 字段,单元测试未通过
【发布时间】:2021-05-18 04:41:26
【问题描述】:

由于 UserEventHistory 类中的 LocalDateTime 字段不匹配,单元测试未通过保存。

有什么办法可以解决这个问题?

data class UserEventHistory(
   val id: Int = 0,
   val login: String,
   val eventType: String,
   val dateCreated: LocalDateTime = LocalDateTime.now()
)

@ExtendWith(MockitoExtension::class)
class UserEventServiceTest(
    @Mock
    private val repository: UserEventRepository) {

    private val service = UserEventServiceImpl(repository)

    companion object {
        private const val LOGIN = "ruabc7"
        private val EVENT_TYPE = EventType.USER_LOGIN
    }

     @Test
     fun save() {
         val userEventHistory = UserEventHistory(
         login = UserEventHistoryServiceTest.LOGIN,
         eventType = UserEventHistoryServiceTest.EVENT_TYPE.toString(),
      )

         service.save(UserEventHistoryServiceTest.LOGIN, 
            UserEventHistoryServiceTest.EVENT_TYPE)

         verify(repository)
             .save(same(userEventHistory))
     }
}

错误信息如下:

Argument(s) are different! Wanted:
repository.save(
UserEventHistory(id=0, login=ruabc7, eventType=USER_LOGIN, dateCreated=2021- 
02-15T12:42:54.348218)
);
-> at ru.raiffeisen.bgt.auth.service.impl.UserEventHistoryServiceTest.save
(UserEventHis 
toryServiceTest.kt:37)
Actual invocation has different arguments:
repository.save(
UserEventHistory(id=0, login=ruabc7, eventType=USER_LOGIN, dateCreated=2021- 
02-15T12:42:54.350623)
);

仓库如下:

@Repository
public interface UserEventRepository : CrudRepository<UserEventHistory, Int> 
{}

【问题讨论】:

  • “UserEventHistory 中 LocalDateTime 字段不匹配”是什么意思?你得到的准确和完整的错误信息是什么?该服务的实施情况如何?当与它相关的所有内容都被嘲笑时,为什么它会被标记为 spring-data-jpa?
  • @JensSchauder 已被编辑。如果您需要更多信息,请告诉我
  • 您还没有发布服务。
  • 与手头问题无关的旁注:您不需要在 Spring Data 存储库上使用 @Repository 注释,这是自动暗示的。
  • 另一个与手头问题无关的旁注:LocalDateTime 没有定义时间点,因此不适合用作时间戳,就像您在这里所做的那样。见blog.schauderhaft.de/2018/03/14/dont-use-localdatetime

标签: unit-testing kotlin spring-data-jpa mockito


【解决方案1】:

大概您的服务使用存储库来保存在服务内部创建的UserEventHistory 实例。

由于这发生在与您用于比较的 userEventHistory 的构造不同的时间,因此两者不同。

要解决此问题,您有多种选择:

UserEventHistory 中更改equals 的实现,因此不考虑日期。这听起来对我来说是错误的,但在技术上肯定是可行的,尽管我不知道如何用 Kotlin 准确地做到这一点。

使用custom matcher 而不是same 来比较UserEventHistory 实例,这会忽略dateCreated 或仅以可能0.1 秒的容差进行粗略比较。

【讨论】:

    猜你喜欢
    • 2013-08-24
    • 2021-12-24
    • 2014-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多