How to use test method of io.kotest.matchers.date.matchers class

Best Kotest code snippet using io.kotest.matchers.date.matchers.test

FailingKotestAsserts.kt

Source:FailingKotestAsserts.kt Github

copy

Full Screen

1package testing.failing2import arrow.core.*3import io.kotest.assertions.arrow.either.shouldBeLeft4import io.kotest.assertions.arrow.either.shouldBeRight5import io.kotest.assertions.arrow.nel.shouldContain6import io.kotest.assertions.arrow.nel.shouldContainNull7import io.kotest.assertions.arrow.option.shouldBeNone8import io.kotest.assertions.arrow.option.shouldBeSome9import io.kotest.assertions.arrow.validation.shouldBeInvalid10import io.kotest.assertions.arrow.validation.shouldBeValid11import io.kotest.assertions.asClue12import io.kotest.assertions.assertSoftly13import io.kotest.assertions.json.*14import io.kotest.assertions.throwables.shouldThrowAny15import io.kotest.assertions.throwables.shouldThrowExactly16import io.kotest.assertions.withClue17import io.kotest.matchers.Matcher18import io.kotest.matchers.MatcherResult19import io.kotest.matchers.booleans.shouldBeFalse20import io.kotest.matchers.booleans.shouldBeTrue21import io.kotest.matchers.collections.shouldBeEmpty22import io.kotest.matchers.collections.shouldBeOneOf23import io.kotest.matchers.collections.shouldBeSameSizeAs24import io.kotest.matchers.collections.shouldBeSorted25import io.kotest.matchers.collections.shouldContain26import io.kotest.matchers.date.shouldBeAfter27import io.kotest.matchers.ints.shouldBeEven28import io.kotest.matchers.ints.shouldBeGreaterThan29import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual30import io.kotest.matchers.ints.shouldBeLessThan31import io.kotest.matchers.ints.shouldBeLessThanOrEqual32import io.kotest.matchers.ints.shouldBeZero33import io.kotest.matchers.maps.shouldBeEmpty34import io.kotest.matchers.maps.shouldContain35import io.kotest.matchers.maps.shouldContainKey36import io.kotest.matchers.maps.shouldContainValue37import io.kotest.matchers.nulls.shouldBeNull38import io.kotest.matchers.should39import io.kotest.matchers.shouldBe40import io.kotest.matchers.shouldNot41import io.kotest.matchers.string.shouldBeBlank42import io.kotest.matchers.string.shouldBeEmpty43import io.kotest.matchers.string.shouldBeUpperCase44import io.kotest.matchers.string.shouldContain45import io.kotest.matchers.string.shouldNotBeBlank46import java.time.LocalDate47import org.junit.jupiter.api.Test48/**49 * Kotest assertions50 *51 * - [Kotest Assertions Documentation](https://kotest.io/assertions/)52 * - [Github](https://github.com/kotest/kotest/)53 */54class FailingKotestAsserts {55    @Test56    fun `General assertions`() {57        assertSoftly {58            "text" shouldBe "txet"59            "hi".shouldBeBlank()60            " ".shouldNotBeBlank()61            "hi".shouldBeEmpty()62            "hi".shouldBeUpperCase()63            "hello".shouldContain("hi")64            false.shouldBeTrue()65            true.shouldBeFalse()66            "not null".shouldBeNull()67            10 shouldBeLessThan 1068            10 shouldBeLessThanOrEqual 969            11 shouldBeGreaterThan 1170            11 shouldBeGreaterThanOrEqual 1271            9.shouldBeEven()72            1.shouldBeZero()73        }74    }75    @Test76    fun `Exception assertions`() {77        assertSoftly {78            shouldThrowExactly<IllegalArgumentException> {79                angryFunction()80            }81            shouldThrowAny {82               "I'm not throwing anything"83            }84        }85    }86    @Test87    fun `Collection assertions`() {88        assertSoftly {89            listOf(1, 2, 3).shouldBeEmpty()90            listOf(1, 2, 3) shouldContain 491            listOf(1, 3, 2).shouldBeSorted()92            listOf(1, 2, 3, 4) shouldBeSameSizeAs listOf(4, 5, 6)93            1 shouldBeOneOf listOf(2, 3)94            mapOf(1 to "one", 2 to "two", 3 to "three").shouldBeEmpty()95            mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainKey 496            mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainValue "five"97            mapOf(1 to "one", 2 to "two", 3 to "three") shouldContain (6 to "six")98        }99    }100    @Test101    fun `Arrow assertions`() {102        assertSoftly {103            val optionNone = none<String>()104            val optionSome = Some("I am something").toOption()105            optionSome.shouldBeNone()106            optionNone.shouldBeSome()107            val rightEither = Either.Right(1)108            val leftEither = Either.Left("ERROR!!")109            leftEither.shouldBeRight()110            leftEither shouldBeRight 1111            rightEither.shouldBeLeft()112            rightEither shouldBeLeft "ERROR!!"113            val nonEmptyList = NonEmptyList.of(1, 2, 3, 4, 5)114            nonEmptyList shouldContain 6115            nonEmptyList.shouldContainNull()116            val valid = Validated.valid()117            val invalid = Validated.invalid()118            invalid.shouldBeValid()119            valid.shouldBeInvalid()120        }121    }122    @Test123    fun `Json assertions`() {124        val jsonString = "{\"test\": \"property\", \"isTest\": true }"125        assertSoftly {126            jsonString shouldMatchJson "{\"test\": \"otherProperty\"}"127            jsonString shouldContainJsonKey "$.anotherTest"128            jsonString shouldNotContainJsonKey "$.test"129            jsonString.shouldContainJsonKeyValue("$.isTest", false)130        }131    }132    @Test133    fun `Custom assertions`() {134        assertSoftly {135            val sentMail = Mail(136                dateCreated = LocalDate.of(2020, 10, 27),137                sent = true, message = "May you have an amazing day"138            )139            val unsentMail = Mail(140                dateCreated = LocalDate.of(2020, 10, 27),141                sent = false, message = "May you have an amazing day"142            )143            // This is possible144            unsentMail.sent should beSent()145            sentMail.sent shouldNot beSent()146            // This is recommended147            unsentMail.shouldBeSent()148            sentMail.shouldNotBeSent()149        }150    }151    @Test152    fun `withClue usage`() {153        val mail = Mail(154            dateCreated = LocalDate.of(2020, 10, 27),155            sent = false, message = "May you have an amazing day"156        )157        withClue("sent field should be true") {158            mail.sent shouldBe true159        }160        mail.asClue {161            it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)162            it.sent shouldBe true163        }164    }165    @Test166    fun `asClue usage`() {167        val mail = Mail(168            dateCreated = LocalDate.of(2020, 10, 27),169            sent = false, message = "May you have an amazing day"170        )171        mail.asClue {172            it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)173            it.sent shouldBe true174        }175    }176    fun beSent() = object : Matcher<Boolean> {177        override fun test(value: Boolean) = MatcherResult(value, "Mail.sent should be true", "Mail.sent should be false")178    }179    fun Mail.shouldBeSent() = this.sent should beSent()180    fun Mail.shouldNotBeSent() = this.sent shouldNot beSent()181}182data class Mail(val dateCreated: LocalDate, val sent: Boolean, val message: String)183fun angryFunction() {184    throw IllegalStateException("How dare you!")185}...

Full Screen

Full Screen

KotestAsserts.kt

Source:KotestAsserts.kt Github

copy

Full Screen

1package testing.asserts2import arrow.core.*3import io.kotest.assertions.arrow.either.shouldBeLeft4import io.kotest.assertions.arrow.either.shouldBeRight5import io.kotest.assertions.arrow.nel.shouldContain6import io.kotest.assertions.arrow.nel.shouldContainNull7import io.kotest.assertions.arrow.option.shouldBeNone8import io.kotest.assertions.arrow.option.shouldBeSome9import io.kotest.assertions.arrow.validation.shouldBeInvalid10import io.kotest.assertions.arrow.validation.shouldBeValid11import io.kotest.assertions.asClue12import io.kotest.assertions.json.*13import io.kotest.assertions.throwables.shouldThrowAny14import io.kotest.assertions.throwables.shouldThrowExactly15import io.kotest.assertions.withClue16import io.kotest.matchers.Matcher17import io.kotest.matchers.MatcherResult18import io.kotest.matchers.booleans.shouldBeFalse19import io.kotest.matchers.booleans.shouldBeTrue20import io.kotest.matchers.collections.shouldBeEmpty21import io.kotest.matchers.collections.shouldBeOneOf22import io.kotest.matchers.collections.shouldBeSameSizeAs23import io.kotest.matchers.collections.shouldBeSorted24import io.kotest.matchers.collections.shouldContain25import io.kotest.matchers.date.shouldBeAfter26import io.kotest.matchers.ints.shouldBeEven27import io.kotest.matchers.ints.shouldBeGreaterThan28import io.kotest.matchers.ints.shouldBeGreaterThanOrEqual29import io.kotest.matchers.ints.shouldBeLessThan30import io.kotest.matchers.ints.shouldBeLessThanOrEqual31import io.kotest.matchers.ints.shouldBeZero32import io.kotest.matchers.maps.shouldBeEmpty33import io.kotest.matchers.maps.shouldContain34import io.kotest.matchers.maps.shouldContainKey35import io.kotest.matchers.maps.shouldContainValue36import io.kotest.matchers.nulls.shouldBeNull37import io.kotest.matchers.should38import io.kotest.matchers.shouldBe39import io.kotest.matchers.shouldNot40import io.kotest.matchers.string.shouldBeBlank41import io.kotest.matchers.string.shouldBeEmpty42import io.kotest.matchers.string.shouldBeUpperCase43import io.kotest.matchers.string.shouldContain44import io.kotest.matchers.string.shouldNotBeBlank45import java.time.LocalDate46import org.junit.jupiter.api.Test47/**48 * Kotest assertions49 *50 * - [Kotest Assertions Documentation](https://kotest.io/assertions/)51 * - [Github](https://github.com/kotest/kotest/)52 */53class KotestAsserts {54    @Test55    fun `General assertions`() {56        "text" shouldBe "text"57        " ".shouldBeBlank()58        "hi".shouldNotBeBlank()59        "".shouldBeEmpty()60        "HI".shouldBeUpperCase()61        "hello".shouldContain("ll")62        true.shouldBeTrue()63        false.shouldBeFalse()64        null.shouldBeNull()65        10 shouldBeLessThan 1166        10 shouldBeLessThanOrEqual 1067        11 shouldBeGreaterThan 1068        11 shouldBeGreaterThanOrEqual 1169        10.shouldBeEven()70        0.shouldBeZero()71    }72    @Test73    fun `Exception assertions`() {74        shouldThrowExactly<IllegalStateException> {75            angryFunction()76        }77        shouldThrowAny {78            angryFunction()79        }80    }81    @Test82    fun `Collection assertions`() {83        emptyList<Int>().shouldBeEmpty()84        listOf(1, 2, 3) shouldContain 385        listOf(1, 2, 3).shouldBeSorted()86        listOf(1, 2, 3) shouldBeSameSizeAs listOf(4, 5, 6)87        1 shouldBeOneOf listOf(1, 2, 3)88        emptyMap<Int, String>().shouldBeEmpty()89        mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainKey 190        mapOf(1 to "one", 2 to "two", 3 to "three") shouldContainValue "two"91        mapOf(1 to "one", 2 to "two", 3 to "three") shouldContain (3 to "three")92    }93    @Test94    fun `Arrow assertions`() {95        val optionNone = none<String>()96        val optionSome = Some("I am something").toOption()97        optionNone.shouldBeNone()98        optionSome.shouldBeSome()99        val rightEither = Either.Right(1)100        val leftEither = Either.Left("ERROR!!")101        rightEither.shouldBeRight()102        rightEither shouldBeRight 1103        leftEither.shouldBeLeft()104        leftEither shouldBeLeft "ERROR!!"105        val nonEmptyList = NonEmptyList.of(1, 2, 3, 4, 5, null)106        nonEmptyList shouldContain 1107        nonEmptyList.shouldContainNull()108        val valid = Validated.valid()109        val invalid = Validated.invalid()110        valid.shouldBeValid()111        invalid.shouldBeInvalid()112    }113    @Test114    fun `Json assertions`() {115        val jsonString = "{\"test\": \"property\", \"isTest\": true }"116        jsonString shouldMatchJson jsonString117        jsonString shouldContainJsonKey "$.test"118        jsonString shouldNotContainJsonKey "$.notTest"119        jsonString.shouldContainJsonKeyValue("$.isTest", true)120    }121    @Test122    fun `Custom assertions`() {123        val sentMail = Mail(124            dateCreated = LocalDate.of(2020, 10, 27),125            sent = true, message = "May you have an amazing day"126        )127        val unsentMail = Mail(128            dateCreated = LocalDate.of(2020, 10, 27),129            sent = false, message = "May you have an amazing day"130        )131        // This is possible132        sentMail.sent should beSent()133        unsentMail.sent shouldNot beSent()134        // This is recommended135        sentMail.shouldBeSent()136        unsentMail.shouldNotBeSent()137    }138    @Test139    fun `withClue usage`() {140        val mail = Mail(141            dateCreated = LocalDate.of(2020, 10, 27),142            sent = false, message = "May you have an amazing day"143        )144        withClue("sent field should be false") {145            mail.sent shouldBe false146        }147        mail.asClue {148            it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)149            it.sent shouldBe false150        }151    }152    @Test153    fun `asClue usage`() {154        val mail = Mail(155            dateCreated = LocalDate.of(2020, 10, 27),156            sent = false, message = "May you have an amazing day"157        )158        mail.asClue {159            it.dateCreated shouldBeAfter LocalDate.of(2020, 10, 26)160            it.sent shouldBe false161        }162    }163    fun beSent() = object : Matcher<Boolean> {164        override fun test(value: Boolean) = MatcherResult(value, "Mail.sent should be true", "Mail.sent should be false")165    }166    fun Mail.shouldBeSent() = this.sent should beSent()167    fun Mail.shouldNotBeSent() = this.sent shouldNot beSent()168}169data class Mail(val dateCreated: LocalDate, val sent: Boolean, val message: String)170fun angryFunction() {171    throw IllegalStateException("How dare you!")172}...

Full Screen

Full Screen

EndToEndTest.kt

Source:EndToEndTest.kt Github

copy

Full Screen

1package io.github.hWorblehat.gradlecumber2import io.github.hWorblehat.gradlecumber.testutil.BASE_PLUGIN_ID3import io.github.hWorblehat.gradlecumber.testutil.projectStruct4import io.github.hWorblehat.gradlecumber.testutil.tempdir5import io.kotest.assertions.throwables.shouldNotThrowAny6import io.kotest.core.spec.style.FreeSpec7import io.kotest.matchers.collections.shouldContainInOrder8import io.kotest.matchers.collections.shouldHaveSize9import io.kotest.matchers.file.exist10import io.kotest.matchers.should11import io.kotest.matchers.shouldBe12import io.kotest.matchers.shouldNotBe13import io.kotest.matchers.string.shouldContain14import org.gradle.testkit.runner.GradleRunner15import org.gradle.testkit.runner.TaskOutcome.*16import java.io.File17class EndToEndTest : FreeSpec({18	"Given a project using the plugin" - {19		val projectDir = tempdir().projectStruct {20			createSettingsFile()21			createBuildFile().writeText("""22					plugins {23						`java`24						id("$BASE_PLUGIN_ID")25					}26					27					import ${GradlecumberPlugin::class.java.`package`.name}.*28					29					repositories {30						jcenter()31					}32					33					val featureTest by cucumber.suites.creating {34						rules { result ->35							if(result.pickle.tags.contains("@failing")) cucumber.OK36							else cucumber.checkResultNotPassedOrSkipped(result)37						}38					}39					40					dependencies {41						cucumber.configurationName(cucumberJava("6.+"))42						"featureTestImplementation"("org.opentest4j:opentest4j:1.2.+")43					}44					45					val strictCheck by tasks.registering {46					47						val msgs = project.tasks48							.named<${CucumberExec::class.simpleName}>(featureTest.cucumberExecTaskName)49							.flatMap { it.formatDestFile("message") }50							51						inputs.file(msgs)52					53						doLast {54							println("Checking cucumber results strictly")55							cucumber.checkCucumberResults {56								messages.fileProvider(msgs)57							}58						}59					}60					61					val checkNoFeatureTestsExist by tasks.registering(${io.github.hWorblehat.gradlecumber.CucumberCheckResults::class.simpleName}::class) {62						messages.fileProvider(project.tasks63							.named<${CucumberExec::class.simpleName}>(featureTest.cucumberExecTaskName)64							.flatMap { it.formatDestFile("message") }65						)66						67						rules { "Test exists when it shouldn't" }68					}69				""".trimIndent())70			createFile("src/main/java/pkg/MyClass.java").writeText("""71				package pkg;72				73				public class MyClass {74					75					private boolean somethingHasBeenDone = false;76					77					public void doSomething() {78						somethingHasBeenDone = true;79					}80					81					public boolean hasSomethingBeenDone() {82						return somethingHasBeenDone;83					}84					85				}86			""".trimIndent())87			createFile("src/featureTest/java/glue/Glue.java").writeText("""88				package glue;89				90				import pkg.MyClass;91				import org.opentest4j.AssertionFailedError;92				import io.cucumber.java.en.*;93				94				public class Glue {95				96					private MyClass testSubject = null;97				98					@Given("MyClass")99					public void givenMyClass() {100						testSubject = new MyClass();101					}102					103					@When("it does something")104					public void whenItDoesSomething() {105						testSubject.doSomething();106					}107					108					@When("nothing is done")109					public void whenNothingIsDone() {110						// do nothing 111					}112					113					@Then("something has been done")114					public void somethingHasBeenDone() {115						if(!testSubject.hasSomethingBeenDone()) {116							throw new AssertionFailedError("Nothing had been done.");117						}118					}119				120				}121			""".trimIndent())122			createFile("src/featureTest/gherkin/pkg/MyClass.feature").writeText("""123				Feature: My Class124				125					Scenario: MyClass remembers when something has been done126						Given MyClass127						When it does something128						Then something has been done129						130					@failing131					Scenario: MyClass remembers when nothing has been done132						Given MyClass133						When nothing is done134						Then something has been done135						136			""".trimIndent())137		}138		val gradleRunner = GradleRunner.create()139			.withPluginClasspath()140			.withProjectDir(projectDir)141		"running 'build' includes the cucumber tests" {142			val result = shouldNotThrowAny { gradleRunner.withArguments("build").build() }143			result.taskPaths(SUCCESS) shouldContainInOrder listOf(144				":classes",145				":cucumberFeatureTest",146				":checkCucumberResultsFeatureTest"147			)148			File(projectDir, "build/cucumberMessages/featureTest/featureTest.ndjson") should exist()149		}150		"running ad-hoc checkCucumberResults works as expected" {151			val result = shouldNotThrowAny { gradleRunner.withArguments("strictCheck").buildAndFail() }152			result.task(":strictCheck").let {153				it shouldNotBe null154				it?.outcome shouldBe FAILED155			}...

Full Screen

Full Screen

TestThatTicketParking.kt

Source:TestThatTicketParking.kt Github

copy

Full Screen

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    }...

Full Screen

Full Screen

helloSpec.kt

Source:helloSpec.kt Github

copy

Full Screen

1package playground2import io.kotest.assertions.print.print3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.assertions.withClue5import io.kotest.core.spec.style.DescribeSpec6import io.kotest.matchers.Matcher7import io.kotest.matchers.MatcherResult8import io.kotest.matchers.shouldBe9import io.kotest.matchers.shouldNot10import io.kotest.matchers.throwable.shouldHaveMessage11import java.time.LocalDate12class HelloSpec : DescribeSpec({13    describe("hello") {14        it("should compare strings") {15            // given:16            val name = "planet"17            // when/then:18            "hello, $name!".shouldBe("hello, world!")19        }20        it("should have a clue and compare strings") {21            withClue("should be string '1'") {22                1.shouldBe("1")23            }24        }25        it("should have exception assertion") {26            shouldThrow<IllegalStateException> {27                error("error message")28            }.shouldHaveMessage("error message")29        }30        it("should format values for assertion error messages") {31            println(1.print())32            println("1".print())33            println(true.print())34            println(null.print())35            println("".print())36            println(listOf(1, 2, 3).print())37            println(listOf(1, 2, listOf(3, 4, listOf(5, 6))).print())38            println(LocalDate.parse("2020-01-02").print())39            data class AvroProduct(val name: String)40            data class Product(val name: String)41            listOf(1, 2).shouldBe(arrayOf(1, 2))42            Product("foo").shouldBe(AvroProduct("foo"))43        }44        it("should use custom matcher") {45            fun containFoo() = object : Matcher<String> {46                override fun test(value: String) = MatcherResult(47                    value.contains("foo"),48                    { "String '$value' should include 'foo'" },49                    { "String '$value' should not include 'foo'" }50                )51            }52            "hello foo".shouldNot(containFoo())53            "hello bar".shouldNot(containFoo())54        }55    }56})57/*58use soft assertions to group assertions.59```60assertSoftly(foo) {61  shouldNotEndWith("b")62  length.shouldBe(3)63}64custom matchers65```66interface Matcher<in T> {67  fun test(value: T): MatcherResult68}69```70*/...

Full Screen

Full Screen

BoardServiceTest.kt

Source:BoardServiceTest.kt Github

copy

Full Screen

1package com.github.njuro.jard.board2import com.github.njuro.jard.TestDataRepository3import com.github.njuro.jard.WithContainerDatabase4import com.github.njuro.jard.board5import io.kotest.assertions.throwables.shouldThrow6import io.kotest.matchers.collections.shouldContainInOrder7import io.kotest.matchers.optional.shouldBeEmpty8import io.kotest.matchers.optional.shouldBePresent9import io.kotest.matchers.shouldBe10import io.kotest.matchers.shouldNotBe11import org.junit.jupiter.api.Test12import org.springframework.beans.factory.annotation.Autowired13import org.springframework.boot.test.context.SpringBootTest14import java.time.OffsetDateTime15@SpringBootTest16@WithContainerDatabase17internal class BoardServiceTest {18    @Autowired19    private lateinit var boardService: BoardService20    @Autowired21    private lateinit var db: TestDataRepository22    @Test23    fun `save board`() {24        val board = board("r", postCounter = 0L)25        val created = boardService.saveBoard(board)26        created.id shouldNotBe null27        created.postCounter shouldBe 1L...

Full Screen

Full Screen

NormalTests.kt

Source:NormalTests.kt Github

copy

Full Screen

1package de.babsek.demo.testingconcepts.part1simpletests2import io.kotest.assertions.json.shouldContainJsonKeyValue3import io.kotest.assertions.json.shouldEqualJson4import io.kotest.assertions.throwables.shouldThrow5import io.kotest.matchers.collections.*6import io.kotest.matchers.date.shouldBeAfter7import io.kotest.matchers.ints.shouldBeGreaterThan8import io.kotest.matchers.should9import io.kotest.matchers.shouldBe10import org.intellij.lang.annotations.Language11import org.junit.jupiter.api.BeforeEach12import org.junit.jupiter.api.Test13import java.time.LocalDate14class NormalTests {15    var x = 516    @BeforeEach17    fun `init tests`() {18        x = 719    }20    @Test21    fun `simple test`() {22        x shouldBe 723    }24    @Test25    fun `numbers are greater or smaller`() {26        7 shouldBeGreaterThan 527    }28    @Test29    fun `true or false`() {30        (7 > 5) shouldBe true31    }32    @Test33    fun `list contains and does not contain element`() {34        (listOf(1, 2) - listOf(1, 2, 3)) should beEmpty()35        (listOf(1, 2) - listOf(2, 3)) shouldHaveSize 136        listOf(1, 2, 3, 4, 5) shouldContain 137        listOf(1, 2, 3, 4, 5) shouldContainInOrder listOf(2, 3)38        listOf(1, 2, 3, 4, 5) shouldNotContain 739    }40    @Test41    fun `something throws`() {42        shouldThrow<IllegalStateException> {43            throw IllegalStateException()44        }45    }46    @Test47    fun `date`() {48        val today = LocalDate.parse("2021-10-14")49        today shouldBeAfter today.minusDays(1)50    }51    @Test52    fun `json`() {53        """{"a": 7}""" shouldEqualJson """{ "a" :7}"""54        testJson55            .shouldContainJsonKeyValue("$.b.field2[1]", 2)56    }57}58@Language("json")59val testJson = """60{61"a": "abcdef",62"b": {63  "field1": "34",64  "field2": [1,2,3]65  }66}67""".trimIndent()...

Full Screen

Full Screen

CreateTrialUserImplTest.kt

Source:CreateTrialUserImplTest.kt Github

copy

Full Screen

1package com.falcon.falcon.core.usecase.trial2import com.falcon.falcon.core.entity.User3import com.falcon.falcon.core.enumeration.UserType4import com.falcon.falcon.core.usecase.user.CreateUserUseCase5import io.kotest.matchers.date.shouldBeBetween6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.shouldBeUUID8import io.kotest.matchers.types.shouldBeTypeOf9import io.mockk.clearAllMocks10import io.mockk.every11import io.mockk.mockk12import org.junit.jupiter.api.BeforeEach13import org.junit.jupiter.api.Test14import org.junit.jupiter.api.TestInstance15import java.time.Instant16import java.time.temporal.ChronoUnit17@TestInstance(TestInstance.Lifecycle.PER_CLASS)18internal class CreateTrialUserImplTest {19    private val createUserUseCase: CreateUserUseCase = mockk()20    private val trialDuration = 1L21    private val underTest: CreateTrialUserImpl = CreateTrialUserImpl(createUserUseCase, trialDuration)22    @BeforeEach...

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1val date = LocalDate.now()2date should beToday()3date should beYesterday()4date should beTomorrow()5date should beBefore(LocalDate.now().plusDays(1))6date should beAfter(LocalDate.now().minusDays(1))7date should beBetween(LocalDate.now().minusDays(1), LocalDate.now().plusDays(1))8date should beBeforeOrEqual(LocalDate.now().plusDays(1))9date should beAfterOrEqual(LocalDate.now().minusDays(1))10date should beBetweenOrEqual(LocalDate.now().minusDays(1), LocalDate.now().plusDays(1))11date should beSameDay(LocalDate.now())12date should beSameMonth(LocalDate.now())13date should beSameYear(LocalDate.now())14date should beSameDayAs(LocalDate.now())15date should beSameMonthAs(LocalDate.now())16date should beSameYearAs(LocalDate.now())17date should beSameDayAs(LocalDate.now(), ChronoUnit.DAYS)18date should beSameMonthAs(LocalDate.now(), ChronoUnit.DAYS)19date should beSameYearAs(LocalDate.now(), ChronoUnit.DAYS)20date should beSameDayAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS)21date should beSameMonthAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS)22date should beSameYearAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS)23date should beSameInstantAs(LocalDate.now())24date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS)25date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS)26date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES)27date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS)28date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS, ChronoUnit.MILLIS)29date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS, ChronoUnit.MILLIS, ChronoUnit.MICROS)30date should beSameInstantAs(LocalDate.now(), ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS, ChronoUnit

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1date.shouldBeToday()2date.shouldNotBeToday()3date.shouldBeYesterday()4date.shouldNotBeYesterday()5date.shouldBeTomorrow()6date.shouldNotBeTomorrow()7date.shouldBeBefore(date)8date.shouldNotBeBefore(date)9date.shouldBeAfter(date)10date.shouldNotBeAfter(date)11date.shouldBeWithin(period, date)12date.shouldNotBeWithin(period, date)13date.shouldBeBetween(date, date)14date.shouldNotBeBetween(date, date)

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1val date = Date(2021, 1, 1)2date should beToday()3date should beTomorrow()4date should beYesterday()5date should beSameDayAs(Date(2021, 1, 1))6date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2))7date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2), Date(2021, 1, 3))8date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2), Date(2021, 1, 3), Date(2021, 1, 4))9date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2), Date(2021, 1, 3), Date(2021, 1, 4), Date(2021, 1, 5))10date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2), Date(2021, 1, 3), Date(2021, 1, 4), Date(2021, 1, 5), Date(2021, 1, 6))11date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2), Date(2021, 1, 3), Date(2021, 1, 4), Date(2021, 1, 5), Date(2021, 1, 6), Date(2021, 1, 7))12date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1, 2), Date(2021, 1, 3), Date(2021, 1, 4), Date(2021, 1, 5), Date(2021, 1, 6), Date(2021, 1, 7), Date(2021, 1, 8))13date should beSameDayAs(Date(2021, 1, 1), Date(2021, 1,

Full Screen

Full Screen

test

Using AI Code Generation

copy

Full Screen

1    import io.kotest.matchers.date.matchers.*2    class DateMatchersTest : FunSpec({3        test("should be same day") {4            val date1 = LocalDate.of(2019, 1, 1)5            val date2 = LocalDate.of(2019, 1, 1)6        }7    })

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful