본문 바로가기

GAB STORY

일상 속 소소한 순간들과 개발 공부 과정에서의 다양한 경험들을 담아낸 공간입니다.
DEVELOPE/Kotlin & Spring

kotlin에서 Clock 시간 Mocking하기

by 갑스토리 2021. 11. 10.
import com.nhaarman.mockitokotlin2.given
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.Mockito.mockStatic
import org.mockito.junit.jupiter.MockitoExtension
import org.springframework.data.projection.ProjectionFactory
import org.springframework.data.projection.SpelAwareProxyProjectionFactory
import java.time.Clock
import java.time.ZonedDateTime

@ExtendWith(MockitoExtension::class)
class MyTest {
   private val clock = Clock.fixed(ZonedDateTime.parse("2021-10-25T00:00:00.000+09:00[Asia/Seoul]").toInstant(), SEOUL_ZONE_ID)
   
    @BeforeEach
    fun setup() {
        runCatching {
            val clockMock = mockStatic(Clock::class.java)
            clockMock.`when`<Clock>(Clock::systemDefaultZone).thenReturn(clock)
        }
    }
    
    @Test
    fun today(){
      assertEquals("2021-10-25T00:00+09:00[Asia/Seoul]", ZonedDateTime.now().toString())
    }
}

댓글