English 中文(简体)
如何与Mockk在科特林模拟本地DateTime ()?
原标题:How do I mock LocalDateTime() in Kotlin with Mockk
I m writing test for a UserService that creates an anonymous user, and part of that includes saving a timestamp at time of creation. The time seems to be mocked properly within the test function itself, but when a timestamp is added in the actual UserService, the real time is being returned. How do I mock it properly? the relevant UserService function is: UserService.kt fun createAnonymousUser(jwt: AuthenticationJsonWebToken): User { val user = User() user.anonUserId = jwt.name user.createdAt = LocalDateTime.now(ZoneOffset.UTC) return userRepository.save(user) } UserService.test.kt @TestInstance(TestInstance.Lifecycle.PER_CLASS) open class UserServiceTest { private val jwt = mockk() private val userRepository = mockk() private val authProperties = AllAuthProperties() private val fixedClock = mockk() private val slotUser = slot() @BeforeTest internal fun init() { clearAllMocks() } @Test fun getMe() { every { jwt.name } returns "anonymous|123" every { LocalDateTime.now() } returns LocalDateTime.MAX val userService = UserService(userRepository, authProperties) val user = User(); user.anonUserId = jwt.name user.createdAt = LocalDateTime.now() every { userRepository.save(capture(slotUser)) } returns user val anonUser = userService.getMe(jwt) verify { userRepository.save(anonUser) } assertEquals(anonUser, user) } } I m just not sure how to accomplish what I m trying.
问题回答
Turns out I had it mostly right; I just needed a slight tweak. verify { userRepository.save(anonUser.capture) } assertEquals(anonUser, user)
mockkStatic(LocalDateTime::ofInstant) every { LocalDateTime.now() } returns LocalDateTime.of(1990, 12, 5, 16, 45)




相关问题
Exposed runs query on all HikariCP open connections

I m running a Ktor server with a PostgreSQL database and just set up the JetBrains Exposed ORM framework with HikariCP for connection pooling (per the recommendation in the Ktor documentation). My ...

SQLite Kotlin issue - no database

I am trying to create boardgamegeek APIs based app in AndroidStudio, however from unknown reason I m getting my database created with no columns. Here s Logical log: (1) no such table: games in "...

Flutter App cannot be installed on Android TV

I m building a Flutter app that should support Android TV and Mobile devices. Despite Google Play shows that it is supported, I cannot install app on my MiBox device. While trying to install it, both ...

热门标签