Best Kotest code snippet using io.kotest.matchers.date.localdatetime
UserServiceTest.kt
Source:UserServiceTest.kt  
1package me.hyungil.user.application.user.service2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.BehaviorSpec4import io.kotest.matchers.shouldBe5import io.kotest.matchers.shouldNotBe6import io.mockk.every7import io.mockk.mockk8import me.hyungil.core.error.exception.ConflictRequestException9import me.hyungil.core.error.exception.NotFoundRequestException10import me.hyungil.user.application.user.port.`in`.GetUserResponse11import me.hyungil.user.application.user.port.`in`.LoginRequest12import me.hyungil.user.application.user.port.`in`.UserRequest13import me.hyungil.user.application.user.port.out.UserPort14import me.hyungil.user.domain.user.User15import java.time.LocalDateTime16internal class UserServiceTest : BehaviorSpec() {17    private val userAdapter: UserPort = mockk(relaxed = true)18    private val userService = UserService(userAdapter)19    init {20        Given("ì ì ë¥¼ ìì±ì ìì²í  ë") {21            val userRequest = UserRequest("hyungil@gmail.com", "12345qwert@")22            `when`("ì´ë¯¸ ì¡´ì¬íë ì´ë©ì¼ì´ë¼ë©´") {23                every { userAdapter.findByEmail(userRequest.email) } answers {24                    User(25                        userRequest.email,26                        userRequest.password,27                        LocalDateTime.now(),28                        null,29                        setOf("USER_ROLE"),30                        131                    )32                }33                val exception = shouldThrow<ConflictRequestException> { userService.createUser(userRequest) }34                Then("ìì¸ë©ìì§ë¥¼ ì¶ë ¥íê³  ì ì  ìì±ì ì¤í¨íë¤,") {35                    exception.message shouldBe "ì´ë¯¸ ì¡´ì¬íë 리ìì¤ì
ëë¤."36                }37            }38            `when`("ì¡´ì¬íë ì´ë©ì¼ì´ ìëë¼ë©´") {39                every { userAdapter.findByEmail(userRequest.email) } returns null40                Then("ì ì  ìì±ì ì±ê³µíë¤") {41                    val user = User(42                        userRequest.email,43                        userRequest.password,44                        LocalDateTime.now(),45                        null,46                        setOf("USER_ROLE"),47                        148                    )49                    every { userAdapter.save(user) } shouldNotBe null50                }51            }52        }53        Given("ë¡ê·¸ì¸ ì") {54            val loginRequest = LoginRequest("hyungil@gmail.com", "12345qwert@")55            `when`("ì¡´ì¬íì§ ìë ì¬ì©ìë¼ë©´") {56                every { userAdapter.findByEmail(loginRequest.email) } returns null57                val exception = shouldThrow<NotFoundRequestException> { userService.login(loginRequest) }58                Then("ìì¸ë©ìì§ë¥¼ ì¶ë ¥íê³  ë¡ê·¸ì¸ì ì¤í¨íë¤.") {59                    exception.message shouldBe "ì¡´ì¬íì§ ìë 리ìì¤ì
ëë¤."60                }61            }62            `when`("ì¡´ì¬íë ì¬ì©ìë¼ë©´") {63                val user = User(64                    loginRequest.email,65                    loginRequest.password,66                    LocalDateTime.now(),67                    null,68                    setOf("USER_ROLE"),69                    170                )71                every { userAdapter.findByEmail(loginRequest.email) } answers { user }72                Then("ë¡ê·¸ì¸ì ì±ê³µíë¤.") {73                    every { user.id?.let { userService.getUserInfo(it) } } shouldNotBe null;74                }75            }76        }77        Given("ì¬ì©ì ì ë³´ë¥¼ ì¡°íí  ë,") {78            val userId = 1L79            `when`("ì¡´ì¬íì§ ìë ì¬ì©ìë¼ë©´") {80                every { userAdapter.findByIdOrNull(userId) } returns null81                val exception = shouldThrow<NotFoundRequestException> { userService.getUserInfo(userId) }82                Then("ìì¸ë©ìì§ë¥¼ ì¶ë ¥íê³  ì¬ì©ì ì ë³´ ì¡°íì ì¤í¨íë¤.") {83                    exception.message shouldBe "ì¡´ì¬íì§ ìë 리ìì¤ì
ëë¤."84                }85            }86            `when`("ì¡´ì¬íë ì¬ì©ìë¼ë©´") {87                val user = User(88                    "user@gmail.com",89                    "QWMEN@#(@#KLMSD!@",90                    LocalDateTime.now(),91                    null,92                    setOf("USER_ROLE"),93                    userId94                )95                every { userAdapter.findByIdOrNull(userId) } answers { user }96                Then("ì¬ì©ì ì ë³´ ì¡°íì ì±ê³µíë¤.") {97                    every { user.id?.let { userService.getUserInfo(it) } } shouldNotBe null98                }99            }100        }101    }102}...PostTest.kt
Source:PostTest.kt  
1package sh.writelog.backend.post.domain2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.FunSpec4import io.kotest.extensions.time.withConstantNow5import io.kotest.matchers.shouldBe6import io.kotest.matchers.shouldNotBe7import java.time.LocalDateTime8internal class PostTest: FunSpec({9    context("create") {10        test("í¬ì¤í¸ë¥¼ ìì±í  ì ìë¤.") {11            val title = "test-title"12            val content = "test-content"13            val createdAt = LocalDateTime.of(2021, 8, 4, 10, 30)14            val lastModifiedAt = LocalDateTime.of(2021, 8, 4, 10, 30)15            val postId = PostId("test-post-id")16            val comment1 = "test-comment-1"17            val comment2 = "test-comment-2"18            val comments = listOf(19                Comment(comment1),20                Comment(comment2)21            )22            val authorId = AuthorId("test-author-id")23            val post = Post.create(24                authorId = authorId,25                postId = postId,26                title = title,27                content = content,28                createdAt = createdAt,29                lastModifiedAt = lastModifiedAt,30                comments = comments31            )32            post shouldNotBe null33            post.authorId shouldBe authorId34            post.postId shouldBe postId35            post.title shouldBe title36            post.content shouldBe content37            post.createdAt shouldBe createdAt38            post.lastModifiedAt shouldBe lastModifiedAt39            post.comments shouldBe comments40        }41        test("ìì± ìê°ì ìì  ìê°ë³´ë¤ ì´íì¼ ì ìë¤.") {42            shouldThrow<IllegalArgumentException> {43                PostFixture.create(44                    LocalDateTime.of(2021, 8, 4, 10, 31),45                    LocalDateTime.of(2021, 8, 4, 10, 30),46                    content = ""47                )48            }49        }50        test("ì ëª©ì ë¹ ë¬¸ìì´ì¼ ì ìë¤.") {51            shouldThrow<IllegalArgumentException> {52                PostFixture.create(title = "", content = "")53            }54        }55        test("ë´ì©ì ë¹ ë¬¸ìì´ì¼ ì ìë¤.") {56            shouldThrow<IllegalArgumentException> {57                PostFixture.create(content = "")58            }59        }60    }61    context("createNew") {62        test("í¬ì¤í¸ ID, ìì± ìê°, ë§ì§ë§ ìì  ìê°, ëê¸ ë¦¬ì¤í¸ ìì´ í¬ì¤í¸ë¥¼ ìì±í  ì ìë¤.") {63            val title = "test-title"64            val content = "test-content"65            val now = LocalDateTime.of(2021, 8, 4, 10, 30)66            val authorId = AuthorId("test-author-id")67            val post = withConstantNow(now) {68                Post.createNew(authorId, title, content)69            }70            post shouldNotBe null71            post.authorId shouldBe authorId72            post.postId shouldNotBe null73            post.title shouldBe title74            post.content shouldBe content75            post.createdAt shouldBe now76            post.lastModifiedAt shouldBe now77            post.comments shouldBe emptyList()78        }79    }80    context("í¸ì§") {81        test("í¬ì¤í¸ì ë³ê²½ ì ìì  ìê°ì´ ë³ê²½ëë¤.") {82            val command = UpdatePostCommand(83                title = "test-title-2",84                content = "test-content-2"85            )86            val post = withConstantNow(LocalDateTime.of(2021, 8, 4, 11, 30)) {87                PostFixture.create(88                    title = "test-title-1",89                    content = "test-content-1",90                    lastModifiedAt = LocalDateTime.now()91                )92            }93            withConstantNow(LocalDateTime.of(2021, 8, 4, 11, 31)) {94                post.update(command)95                post.title shouldBe "test-title-2"96                post.content shouldBe "test-content-2"97                post.lastModifiedAt shouldBe LocalDateTime.now()98            }99        }100        test("í¬ì¤í¸ ë³ê²½ ì ì ëª©ì ë¹ ë¬¸ìì´ì¼ ì ìë¤.") {101            val post = PostFixture.create(102                title = "post title",103                content = "content"104            )105            val command = UpdatePostCommand(106                title = ""107            )108            shouldThrow<IllegalArgumentException> {109                post.update(command)110            }111        }112        test("í¬ì¤í¸ ë³ê²½ ì ë´ì©ì ë¹ ë¬¸ìì´ì¼ ì ìë¤.") {113            val post = PostFixture.create(114                title = "post title",115                content = "content"116            )117            val command = UpdatePostCommand(118                title = "title",119                content = ""120            )121            shouldThrow<IllegalArgumentException> {122                post.update(command)123            }124        }125    }126})...BoardServiceFunSpecSemSpringTest.kt
Source:BoardServiceFunSpecSemSpringTest.kt  
1package nitrox.org.ktboard.application.service2import com.ninjasquad.springmockk.MockkBean3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.FunSpec5import io.kotest.core.test.TestCase6import io.kotest.extensions.spring.SpringExtension7import io.kotest.matchers.collections.shouldBeIn8import io.kotest.matchers.longs.shouldBeExactly9import io.kotest.matchers.should10import io.kotest.matchers.shouldBe11import io.kotest.matchers.string.startWith12import io.mockk.clearMocks13import io.mockk.every14import io.mockk.junit5.MockKExtension15import io.mockk.verify16import nitrox.org.ktboard.domain.board.Board17import nitrox.org.ktboard.domain.board.Column18import nitrox.org.ktboard.domain.board.Task19import nitrox.org.ktboard.extensions.KBoardFunSpec20import nitrox.org.ktboard.infrastructure.bd.BoardRepositoryJPA21import org.junit.jupiter.api.extension.ExtendWith22import org.springframework.boot.test.context.SpringBootTest23import org.springframework.test.context.junit.jupiter.SpringExtension24import java.time.LocalDateTime25@ExtendWith(MockKExtension::class)26@SpringBootTest27internal class BoardServiceFunSpecSemSpringTest(boardService: BoardService) : FunSpec() {28    override fun extensions() = listOf(SpringExtension)29    @MockkBean30    private lateinit var boardRepository: BoardRepositoryJPA31    override fun beforeTest(testCase: TestCase) {32        clearMocks(boardRepository)33    }34    init {35        test("Arquivar quadros sem colunas").config(invocations = 3) {36            val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())37            every { boardRepository.save(board)} returns board38            every { boardRepository.findByIdOrNull(1L)} returns board39            val resultBoad = boardService.finishBoard(1L)40            verify { boardRepository.save(board) }41            resultBoad!!.id shouldBeExactly board.id42            resultBoad!!.name shouldBe board.name43        }44        test("Arquivar quadros com colunas e sem tarefas") {45            val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())46            val column = Column(1L, "Backlog", LocalDateTime.now())47            board.columns = listOf<Column>(column)48            every { boardRepository.save(board)} returns board49            every { boardRepository.findByIdOrNull(1L)} returns board50            val resultBoad = boardService.finishBoard(1L)51            resultBoad!!.id shouldBeExactly board.id52            resultBoad!!.name shouldBe board.name53        }54        test("Arquivar quadros sem colunas e com tarefas finalizadas").config(invocations = 3) {55            val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())56            val column = Column(1L, "Backlog", LocalDateTime.now())57            board.columns = listOf<Column>(column)58            val finalizedTask = Task(1L, "Contruir serviço x", "contruir serviço necessário",59                LocalDateTime.now(), LocalDateTime.now().plusMonths(1)).apply {60                this.finalized = true61            }62            column.tasks = listOf<Task>(finalizedTask)63            every { boardRepository.save(board)} returns board64            every { boardRepository.findByIdOrNull(1L)} returns board65            val resultBoad = boardService.finishBoard(1L)66            resultBoad!!.id shouldBeExactly board.id67            resultBoad!!.name shouldBe board.name68            finalizedTask shouldBeIn resultBoad.allTasks()69        }70        test("Arquivar quadros sem colunas e com tarefas ativas") {71            val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())72            val column = Column(1L, "Backlog", LocalDateTime.now())73            val activeTask = Task(1L, "Contruir serviço x", "contruir serviço necessário",74                    LocalDateTime.now(), LocalDateTime.now().plusMonths(1))75            column.tasks = listOf<Task>(activeTask)76            board.columns = listOf<Column>(column)77            every { boardRepository.findByIdOrNull(1L)} returns board78            val exception = shouldThrow<RuntimeException> {79                boardService.finishBoard(1L)80            }81            verify(exactly = 0) { boardRepository.save(board) }82            exception.message should startWith("Não é possivel arquivar")83        }84    }85}...BoardServiceAnnotationSpecSpringTest.kt
Source:BoardServiceAnnotationSpecSpringTest.kt  
1package nitrox.org.ktboard.application.service2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.AnnotationSpec4import io.kotest.matchers.collections.shouldBeIn5import io.kotest.matchers.longs.shouldBeExactly6import io.kotest.matchers.should7import io.kotest.matchers.shouldBe8import io.kotest.matchers.string.startWith9import io.mockk.clearMocks10import io.mockk.every11import io.mockk.mockk12import io.mockk.verify13import nitrox.org.ktboard.domain.board.Board14import nitrox.org.ktboard.domain.board.Column15import nitrox.org.ktboard.domain.board.Task16import nitrox.org.ktboard.infrastructure.bd.BoardRepositoryJPA17import java.time.LocalDateTime18internal class BoardServiceAnnotationSpecSpringTest : AnnotationSpec() {19    private lateinit var boardService: BoardService20    private val boardRepository: BoardRepositoryJPA = mockk<BoardRepositoryJPA>()21    @BeforeEach22    fun beforeTest() {23        clearMocks(boardRepository)24        boardService = BoardService(boardRepository)25    }26    @Test27    fun finishBoardWithNoColumns() {28        val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())29        every { boardRepository.save(board)} returns board30        every { boardRepository.findByIdOrNull(1L)} returns board31        val resultBoad = boardService.finishBoard(1L)32        verify { boardRepository.save(board) }33        resultBoad!!.id shouldBeExactly board.id34        resultBoad.name shouldBe board.name35    }36    @Test37    fun finishBoardWithColumnsAndNoTasks() {38        val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())39        val column = Column(1L, "Backlog", LocalDateTime.now())40        board.columns = listOf<Column>(column)41        every { boardRepository.save(board)} returns board42        every { boardRepository.findByIdOrNull(1L)} returns board43        val resultBoad = boardService.finishBoard(1L)44        resultBoad!!.id shouldBeExactly board.id45        resultBoad.name shouldBe board.name46    }47    @Test48    fun finishBoardWithColumnsAndNoActiveTasks() {49        val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())50        val column = Column(1L, "Backlog", LocalDateTime.now())51        val finalizedTask = Task(1L, "Contruir serviço x", "contruir serviço necessário",52            LocalDateTime.now(), LocalDateTime.now().plusMonths(1)).apply {53            this.finalized = true54        }55        column.tasks = listOf<Task>(finalizedTask)56        board.columns = listOf<Column>(column)57        every { boardRepository.save(board)} returns board58        every { boardRepository.findByIdOrNull(1L)} returns board59        val resultBoad = boardService.finishBoard(1L)60        resultBoad!!.id shouldBeExactly board.id61        resultBoad.name shouldBe board.name62        finalizedTask shouldBeIn resultBoad.allTasks()63    }64    @Test65    fun finishBoardWithColumnsAndActiveTasks() {66        val board = Board(1L, "Projeto X", "Projeto do produto X", LocalDateTime.now())67        val column = Column(1L, "Backlog", LocalDateTime.now())68        val activeTask = Task(1L, "Contruir serviço x", "contruir serviço necessário",69            LocalDateTime.now(), LocalDateTime.now().plusMonths(1))70        val finalizedTask = Task(2L, "Contruir serviço y", "contruir serviço necessário",71            LocalDateTime.now(), LocalDateTime.now().plusMonths(1)).apply {72            this.finalized = true73        }74        column.tasks = listOf<Task>(activeTask, finalizedTask)75        board.columns = listOf<Column>(column)76        every { boardRepository.findByIdOrNull(1L)} returns board77        val exception = shouldThrow<RuntimeException> {78            boardService.finishBoard(1L)79        }80        verify(exactly = 0) { boardRepository.save(board) }81        exception.message should startWith("Não é possivel arquivar")82    }83}...TestThatTicketParking.kt
Source:TestThatTicketParking.kt  
1package exercice_12import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.comparables.shouldBeLessThan4import io.kotest.matchers.shouldBe5import io.kotest.matchers.shouldNotBe6import java.time.LocalDateTime7class TestThatTicketParking : StringSpec({8//    "Test vraiment peu fiable => test fragile" {9//        // Arrange10//        val ticket = Ticket(immatriculation = "AA-000-XX")11//12//        // Act13//        ticket.imprime() // Ici le temps est probablement calculé quelque au sein de cette méthode14//        // Et si nous pouvions être les maitres du temps ?15//16//        // Assert17//        ticket.horodatage shouldBe LocalDateTime.now()18//    }19    //premier pas vers un contrôle du temps20    "Maitrisons le temps, heure fixe sur MIN" {21        // Arrange22        val ticket = Ticket(immatriculation = "AA-000-XX", horloge = LocalDateTime.MIN)23        // Act24        ticket.imprime() // Ici le temps est probablement calculé quelque au sein de cette méthode25        // Et si nous pouvions être les maitres du temps ?26        // Assert27        ticket.horodatage shouldBe LocalDateTime.MIN28    }29    // conclusion partielle,30    // mais on du changer notre code de prod31    // çà ne fait plus le taf attendu32//    fun imprime() {33//        dateInterne = LocalDateTime.now()34//        dateInterne = horloge35//    }36    // on veut pouvoir garder l'appel sur une horloge avec un now()37    // est-ce quelqu'un a une idée ?38    // si on créé une objet respectant ce contrat ?39    "un flag de test" {40        // Arrange41        val ticket = Ticket2(immatriculation = "AA-000-XX")42        // Act43        ticket.environementDeTest(actif=true)44        ticket.imprime()45        // Assert46        ticket.horodatage shouldBe LocalDateTime.MIN47    }48    // conclusion: est ce une bonne chose de modifier le code de prod pour faire passer le test?49    // conclusion bis: le code ne doit pas bouger si on est en mode test ou en mode prod50    // ce qui change, c'est la facon de retourner le temps: il faut un temps de test, et un temps de prod51    "Maitrisons le temps" {52        // Arrange53        val ticket = Ticket4(immatriculation = "AA-000-XX", horlogeExterne = StubHorloge() )54        // Act55        ticket.imprime() // Ici le temps est  uniquement obtenu au sein de cette méthode56        // nous sommes les maitres du temps dans le Stub57        // Assert58        ticket.horodatage shouldBe StubHorloge().now()59    }60    "Testons le tout avec le temps en production" {61        // Arrange62        val ticket = Ticket4(immatriculation = "AA-000-XX", horlogeExterne = HorlogeExterne() )63        // Act64        ticket.imprime() // Ici le temps est  uniquement obtenu au sein de cette méthode65        // nous sommes les maitres du temps dans le Stub66        // Assert67        ticket.horodatage!! shouldBeLessThan  HorlogeExterne().now()68    }69    "testons juste l'horloge' en production" {70        HorlogeExterne().now() shouldNotBe HorlogeExterne().now()71    }72    "testons juste l'horloge de stub" {73        StubHorloge().now() shouldBe StubHorloge().now()74    }75    "testons juste l'horloge' fake" {76        val horlogeUnique = FakeHorloge()77        horlogeUnique.now() shouldBeLessThan  horlogeUnique.now()78    }79    "Deux tickets sont émis séquentiellement" {80        // Arrange81        val horlogeUnique = FakeHorloge()82        val ticket1 = Ticket4(immatriculation = "AA-000-XX", horlogeExterne =  horlogeUnique)83        val ticket2 = Ticket4(immatriculation = "AA-000-XX", horlogeExterne = horlogeUnique )84        // Act85        ticket1.imprime() // Ici le temps est  uniquement obtenu au sein de cette méthode86        ticket2.imprime()87        // Assert88        ticket1.horodatage!! shouldBeLessThan  ticket2.horodatage!!89    }90})...UserTest.kt
Source:UserTest.kt  
1package sh.writelog.backend.user.domain2import io.kotest.core.spec.DisplayName3import io.kotest.core.spec.style.FunSpec4import io.kotest.extensions.time.withConstantNow5import io.kotest.matchers.shouldBe6import io.kotest.matchers.shouldNotBe7import java.time.LocalDateTime8@DisplayName("ì¬ì©ì ëª
ì¸")9internal class UserTest : FunSpec({10    val nickname = Nickname("test-nickname")11    val email = Email("test@email.com")12    val imageUrl = "test-url"13    val bio = "test-bio"14    val profile = Profile(15        nickname = nickname,16        email = email,17        imageUrl = imageUrl,18        bio = bio19    )20    context("ìì±") {21        context("create") {22            test("ì¬ì©ìë ID, íë¡í, íìê°ì
 ìê° ë§ì§ë§ ì ë³´ ë³ê²½ ìê°ì ì´ì©í´ ìì±í  ì ìë¤.") {23                val userId = UserId("test-user-id")24                val createdAt = LocalDateTime.of(2021, 8, 23, 23, 0)25                val lastModifiedAt = LocalDateTime.of(2021, 8, 23, 23, 0)26                val uut = User.create(27                    id = userId,28                    profile = profile,29                    createdAt = createdAt,30                    lastModifiedAt = lastModifiedAt,31                )32                uut.id shouldBe userId33                uut.profile shouldBe profile34                uut.createdAt shouldBe createdAt35                uut.lastModifiedAt shouldBe lastModifiedAt36            }37        }38        context("createNew") {39            val now = LocalDateTime.of(2021, 8, 23, 23, 0)40            test("ì¬ì©ìë íë¡íì ì´ì©í´ ìì±í  ì ìë¤.") {41                val uut = withConstantNow(now) {42                    User.createNew(profile = profile)43                }44                uut.id shouldNotBe null45                uut.profile shouldBe profile46                uut.createdAt shouldBe now47                uut.lastModifiedAt shouldBe now48            }49        }50    }51    context("nickname()") {52        test("ëë¤ìì ë°ííë¤.") {53            User.createNew(profile = profile).nickname() shouldBe nickname54        }55    }56    context("email()") {57        test("ì´ë©ì¼ì ë°ííë¤.") {58            User.createNew(profile = profile).email() shouldBe email59        }60    }61    context("profileImageUrl()") {62        test("íë¡í ì´ë¯¸ì§ë¥¼ ë°ííë¤.") {63            User.createNew(profile = profile).profileImageUrl() shouldBe imageUrl64        }65    }66    context("bio()") {67        test("bio를 ë°ííë¤.") {68            User.createNew(profile = profile).bio() shouldBe bio69        }70    }71})...OrderPaymentRepositoryTest.kt
Source:OrderPaymentRepositoryTest.kt  
1package com.thoughtworks.userorder.repository2import com.thoughtworks.userorder.common.PaymentChannel3import com.thoughtworks.userorder.repository.entity.OrderPayment4import io.kotest.core.extensions.install5import io.kotest.core.spec.style.StringSpec6import io.kotest.extensions.spring.SpringExtension7import io.kotest.extensions.testcontainers.JdbcTestContainerExtension8import io.kotest.matchers.shouldBe9import io.kotest.matchers.shouldNotBe10import kotlinx.coroutines.Dispatchers11import kotlinx.coroutines.withContext12import org.springframework.boot.test.context.SpringBootTest13import org.springframework.test.context.ContextConfiguration14import java.time.LocalDateTime15@SpringBootTest16@ContextConfiguration(initializers = [Initializer::class])17class OrderPaymentRepositoryTest(val orderPaymentRepository: OrderPaymentRepository) : StringSpec({18    val ds = install(JdbcTestContainerExtension(mysql))19    "should save OrderPayment when call save given OrderPayment" {20        val order = withContext(Dispatchers.IO) {21            orderPaymentRepository.save(22                OrderPayment(23                    null,24                    1L,25                    PaymentChannel.WECHAT_PAY,26                    "http://mock.pay",27                    LocalDateTime.now(),28                    LocalDateTime.now().plusMinutes(5),29                    10.030                )31            )32        }33        order.id shouldNotBe null34        order.orderId shouldBe 1L35    }36}) {37    override fun extensions() = listOf(SpringExtension)38}...DateTimeString.kt
Source:DateTimeString.kt  
1package com.musinsa.shared.test.matchers.string2import io.kotest.assertions.throwables.shouldNotThrow3import io.kotest.matchers.Matcher4import io.kotest.matchers.MatcherResult5import io.kotest.matchers.shouldNotBe6import java.time.LocalDateTime7import java.time.format.DateTimeFormatter8import java.time.format.DateTimeParseException9private fun toLocalDateTime(value: String): LocalDateTime {10    return LocalDateTime.parse(value, DateTimeFormatter.ISO_DATE_TIME)11}12fun <T> beValidISODateTimeString(): Matcher<String?> = object : Matcher<String?> {13    override fun test(value: String?): MatcherResult {14        val passed = if (value == null) false else try {15            toLocalDateTime(value)16            true17        } catch (e: DateTimeParseException) {18            false19        }20        return MatcherResult(21            passed,22            { "\"$value\" should be valid date-time string" },23            { "\"$value\" should not be valid date-time string" }24        )25    }26}27fun String?.shouldValidISODateTimeString() {28    this shouldNotBe null29    shouldNotThrow<DateTimeParseException> {30        toLocalDateTime(this as String)31    }32}...localdatetime
Using AI Code Generation
1    import io.kotest.matchers.date.localDateTime2    import io.kotest.matchers.date.localDate3    import io.kotest.matchers.date.localTime4    import io.kotest.matchers.date.offsetDateTime5    import io.kotest.matchers.date.zonedDateTime6    import io.kotest.matchers.date.instant7    import io.kotest.matchers.date.duration8    import io.kotest.matchers.date.period9    import io.kotest.matchers.date.year10    import io.kotest.matchers.date.month11    import io.kotest.matchers.date.day12    import io.kotest.matchers.date.hour13    import io.kotest.matchers.date.minute14    import io.kotest.matchers.date.second15    import io.kotest.matchers.date.millisecond16    import io.kotest.matchers.date.nanosecond17    import io.kotest.matchers.date.zoneOffset18    import iolocaldatetime
Using AI Code Generation
1val dateTime = LocalDateTime.now()2val date = LocalDate.now()3val time = LocalTime.now()4val zonedDateTime = ZonedDateTime.now()5val instant = Instant.now()6val zoneId = ZoneId.systemDefault()7val duration = Duration.of(1, ChronoUnit.DAYS)8val period = Period.of(1, 1, 1)9val year = Year.of(2020)10val yearMonth = YearMonth.of(2020, 4)11val monthDay = MonthDay.of(4, 20)12val offsetTime = OffsetTime.now()13val offsetDateTime = OffsetDateTime.now()14val period = Period.of(1, 1, 1)15val year = Year.of(2020)16val yearMonth = YearMonth.of(2020, 4)localdatetime
Using AI Code Generation
1val date = LocalDateTime.of(2020, 1, 1, 0, 0, 0)2date.shouldBeBetween(LocalDateTime.of(2019, 1, 1, 0, 0, 0), LocalDateTime.of(2021, 1, 1, 0, 0, 0))3val date = LocalDateTime.of(2020, 1, 1, 0, 0, 0)4date.shouldBeBetween(LocalDateTime.of(2019, 1, 1, 0, 0, 0), LocalDateTime.of(2021, 1, 1, 0, 0, 0))5val date = LocalDateTime.of(2020, 1, 1, 0, 0, 0)6date.shouldBeBetween(LocalDateTime.of(2019, 1, 1, 0, 0, 0), LocalDateTime.of(2021, 1, 1, 0, 0, 0))7val date = LocalDateTime.of(2020, 1, 1, 0, 0, 0)8date.shouldBeBetween(LocalDateTime.of(2019, 1, 1, 0, 0, 0), LocalDateTime.of(2021, 1, 1, 0, 0, 0))9val date = LocalDateTime.of(2020, 1, 1, 0, 0, 0)10date.shouldBeBetween(LocalDateTime.of(2019, 1, 1, 0, 0, 0), LocalDateTime.of(2021, 1, 1, 0, 0, 0))11val date = LocalDateTime.of(2020, 1, 1, 0, 0, 0)12date.shouldBeBetween(LocalDateTime.of(2019, 1, 1, 0, 0, 0), LocalDateTime.of(2021, 1, 1, 0, 0, 0))localdatetime
Using AI Code Generation
1val localDateTime = LocalDateTime.now()2localDateTime shouldBe between(LocalDateTime.now().minusSeconds(2), LocalDateTime.now().plusSeconds(2))3val localDate = LocalDate.now()4localDate shouldBe between(LocalDate.now().minusDays(2), LocalDate.now().plusDays(2))5val localTime = LocalTime.now()6localTime shouldBe between(LocalTime.now().minusHours(2), LocalTime.now().plusHours(2))7val instant = Instant.now()8instant shouldBe between(Instant.now().minusSeconds(2), Instant.now().plusSeconds(2))9val zonedDateTime = ZonedDateTime.now()10zonedDateTime shouldBe between(ZonedDateTime.now().minusSeconds(2), ZonedDateTime.now().plusSeconds(2))11val zonedDate = ZonedDateTime.now().toLocalDate()12zonedDate shouldBe between(ZonedDateTime.now().minusDays(2), ZonedDateTime.now().plusDays(2))13val zonedTime = ZonedDateTime.now().toLocalTime()14zonedTime shouldBe between(ZonedDateTime.now().minusHours(2), ZonedDateTime.now().plusHours(2))15val offsetDateTime = OffsetDateTime.now()16offsetDateTime shouldBe between(OffsetDateTime.now().minusSeconds(2), OffsetDateTime.now().plusSeconds(2))17val offsetDate = OffsetDateTime.now().toLocalDate()18offsetDate shouldBe between(OffsetDateTime.now().minusDays(2), OffsetDateTime.now().plusDays(2))19val offsetTime = OffsetDateTime.now().toLocalTime()20offsetTime shouldBe between(OffsetDateTime.now().minusHours(2), OffsetDateTime.now().plusHours(2))21val date = Date()22date shouldBe between(Date(System.currentTimeMillislocaldatetime
Using AI Code Generation
1val date = LocalDateTime(2019, 3, 18, 12, 0, 0)2date.shouldBeBetween(LocalDateTime(2019, 3, 18, 11, 59, 59), LocalDateTime(2019, 3, 18, 12, 0, 1))3val date = LocalDate(2019, 3, 18)4date.shouldBeBetween(LocalDate(2019, 3, 17), LocalDate(2019, 3, 19))5val date = LocalTime(12, 0, 0)6date.shouldBeBetween(LocalTime(11, 59, 59), LocalTime(12, 0, 1))7val date = Instant.ofEpochMilli(1552905600000)8date.shouldBeBetween(Instant.ofEpochMilli(1552905599999), Instant.ofEpochMilli(1552905600001))9val date = ZonedDateTime.of(2019, 3, 18, 12, 0, 0, 0, ZoneId.of("UTC"))10date.shouldBeBetween(ZonedDateTime.of(2019, 3, 18, 11, 59, 59, 0, ZoneId.of("UTC")), ZonedDateTime.of(2019, 3, 18, 12, 0, 1, 0, ZoneId.of("UTC")))11val date = OffsetDateTime.of(2019, 3, 18, 12, 0, 0, 0, ZoneOffset.UTC)12date.shouldBeBetween(OffsetDateTime.of(2019, 3, 18, 11, 59, 59, 0, ZoneOffset.UTC), OffsetDateTime.of(2019, 3, 18, 12, 0, 1, 0, ZoneOffset.UTC))13val date = OffsetTime.of(12, 0, 0, 0, ZoneOffset.UTC)14date.shouldBeBetween(OffsetTime.of(11, 59,localdatetime
Using AI Code Generation
1localDateTime1.shouldBeAfter(localDateTime2)2localDateTime1.isAfter(localDateTime2) shouldBe true3localDateTime1.shouldBeAfter(localDateTime2)4localDateTime1.isAfter(localDateTime2) shouldBe true5localDateTime1.shouldBeAfter(localDateTime2)6localDateTime1.isAfter(localDateTime2) shouldBe true7localDateTime1.shouldBeAfter(localDateTime2)8localDateTime1.isAfter(localDateTime2) shouldBe true9localDateTime1.shouldBeAfter(localDateTime2)10localDateTime1.isAfter(localDateTime2) shouldBe true11localDateTime1.shouldBeAfter(localDateTime2)12localDateTime1.isAfter(localDateTime2) shouldBe true13import io.kotest.matchers.date.shouldBelocaldatetime
Using AI Code Generation
1import io.kotest.matchers.date.*2import java.time.*3import java.time.format.*4import java.util.*5fun main(args: Array<String>) {6val date = LocalDateTime.of(2019, Month.APRIL, 1, 10, 30)7println(date)8val date1 = LocalDateTime.of(2019, Month.APRIL, 1, 10, 30)9println(date1)10}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
