Best Kotest code snippet using io.kotest.matchers.should.test
ServerTest.kt
Source:ServerTest.kt
...21 * SOFTWARE.22 *23 */24package ttgamelib.net25import io.kotest.core.spec.style.FunSpec26import io.kotest.data.forAll27import io.kotest.data.row28import io.kotest.inspectors.forAll29import io.kotest.matchers.booleans.shouldBeFalse30import io.kotest.matchers.booleans.shouldBeTrue31import io.kotest.matchers.collections.shouldBeEmpty32import io.kotest.matchers.collections.shouldContain33import io.kotest.matchers.collections.shouldHaveSize34import io.kotest.matchers.maps.shouldContainValue35import io.kotest.matchers.shouldBe36import io.kotest.matchers.shouldNotBe37import io.kotest.matchers.types.shouldBeInstanceOf38import io.kotest.matchers.types.shouldBeTypeOf39import io.ktor.http.cio.websocket.*40import io.mockk.*41import kotlinx.serialization.json.Json42import ttgamelib.GameEngine43private inline fun<reified T: Packet> List<Frame>.decode(): List<T> {44 return map {45 Json.decodeFromString(Packet.serializer(), (it as Frame.Text).readText()) as T46 }47}48private fun createConnection(userName: String, clientId: Int): Pair<ClientConnection, MutableList<Frame>> {49 val sentPackets = mutableListOf<Frame>()50 val session = mockk<DefaultWebSocketSession>().also {51 coEvery {52 it.send(capture(sentPackets))53 } just Runs54 }55 val connection = ClientConnection(session).apply {56 name = userName57 id = clientId58 }59 return connection to sentPackets60}61internal class ServerTest : FunSpec({62 val engine = mockk<GameEngine>(relaxed = true)63 val (connection, sentPackets) = createConnection("player1", 1)64 lateinit var server: Server65 beforeEach {66 sentPackets.clear()67 }68 context("SendNamePacket") {69 val userName = "New User"70 server = Server("localhost", 1000, engine)71 test("should create new user if name is not in use") {72 server.handlePacket(SendNamePacket(userName), connection)73 val sent = sentPackets.decode<Packet>()74 sent[0].shouldBeInstanceOf<InitClientPacket>()75 (sent[0] as InitClientPacket).clientId shouldBe connection.id76 sent[1].shouldBeInstanceOf<ChatMessagePacket>()77 coVerify {78 engine.playerConnected(connection.id, userName)79 }80 }81 test("should request another name if in use") {82 val (connection2, sentPackets2) = createConnection("player2", 2)83 server.handlePacket(SendNamePacket(userName), connection2)84 val sent = sentPackets2.decode<SuggestNamePacket>()85 with (sent[0]) {86 name shouldNotBe userName87 taken.shouldContain(userName)88 disconnected.shouldBeFalse()89 }90 }91 test("should check for reconnection if disconnected") {92 server.connections.remove(connection.id)93 server.handlePacket(SendNamePacket(userName), connection)94 val sent = sentPackets.decode<SuggestNamePacket>()95 with (sent[0]) {96 name shouldNotBe userName97 taken.shouldContain(userName)98 disconnected.shouldBeTrue()99 }100 }101 test("should replace player on reconnection") {102 server.handlePacket(SendNamePacket(userName, true), connection)103 val sent = sentPackets.decode<Packet>()104 sent[0].shouldBeInstanceOf<InitClientPacket>()105 (sent[0] as InitClientPacket).clientId shouldBe connection.id106 sent[1].shouldBeInstanceOf<ChatMessagePacket>()107 coVerify {108 engine.playerReconnected(connection.id)109 }110 }111 test("should not replace player that is connected") {112 server.handlePacket(SendNamePacket(userName, true), connection)113 val sent = sentPackets.decode<SuggestNamePacket>()114 with (sent[0]) {115 name shouldNotBe userName116 disconnected.shouldBeFalse()117 }118 }119 }120 test("GameCommandPacket should be sent to game engine") {121 val packet = MessagePacket(object : GameMessage{})122 server.handlePacket(packet, connection)123 sentPackets.shouldBeEmpty()124 coVerify {125 engine.handle(connection.id, packet)126 }127 }128 context("chat command") {129 server = Server("localhost", 1000, engine)130 val connections = mutableListOf<ClientConnection>()131 val outgoing = mutableListOf<MutableList<Frame>>()132 for (i in 1..3) {133 with (createConnection("player$i", i)) {134 connections += first135 outgoing += second136 server.handlePacket(SendNamePacket(first.name), first)137 }138 }139 beforeEach {140 outgoing.forEach { it.clear() }141 }142 test("there should be three connected players") {143 connections.forAll {144 server.connections.shouldContainValue(it)145 }146 }147 test("emote should send message to all users") {148 forAll(149 row("/em is here"),150 row("/me is here")151 ) { msg ->152 server.handlePacket(ChatCommandPacket(connection.id, msg), connection)153 }154 outgoing.forEach {155 with (it.decode<ChatMessagePacket>()) {156 shouldHaveSize(2)157 forAll { it.message.shouldBeTypeOf<EmoteMessage>() }158 }159 }160 }161 test("whisper should send message to one user") {162 server.handlePacket(ChatCommandPacket(connections[0].id, "/w player2 a secret"), connections[0])163 outgoing[0].shouldHaveSize(1)164 outgoing[1].shouldHaveSize(1)165 outgoing[2].shouldBeEmpty()166 }167 test("whisper to unknown user should send info message to sender") {168 server.handlePacket(ChatCommandPacket(connections[1].id, "/w nobody a secret"), connections[1])169 outgoing[0].shouldHaveSize(0)170 outgoing[2].shouldHaveSize(0)171 outgoing[1].shouldHaveSize(1)172 outgoing[1].decode<ChatMessagePacket>().forAll {173 it.message.shouldBeTypeOf<InfoMessage>()174 }175 }176 test("unknown command should send info message to sender") {177 server.handlePacket(ChatCommandPacket(connections[1].id, "/foo bar baz"), connections[1])178 outgoing[0].shouldHaveSize(0)179 outgoing[2].shouldHaveSize(0)180 outgoing[1].shouldHaveSize(1)181 outgoing[1].decode<ChatMessagePacket>().forAll {182 it.message.shouldBeTypeOf<InfoMessage>()183 }184 }185 }186})...
RoomsKtTest.kt
Source:RoomsKtTest.kt
1package com.tylerkindy.betrayal.db2import com.tylerkindy.betrayal.Direction3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.DescribeSpec5import io.kotest.matchers.collections.shouldBeEmpty6import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder7import io.kotest.matchers.should8import io.kotest.matchers.shouldBe9import io.kotest.property.Arb10import io.kotest.property.Exhaustive11import io.kotest.property.arbitrary.ShortShrinker12import io.kotest.property.arbitrary.arbitrary13import io.kotest.property.arbitrary.enum14import io.kotest.property.arbitrary.set15import io.kotest.property.checkAll16import io.kotest.property.exhaustive.ints17import io.kotest.property.exhaustive.map18import io.kotest.property.forAll19import org.jetbrains.exposed.sql.insert20import org.jetbrains.exposed.sql.select21import org.jetbrains.exposed.sql.selectAll22import org.jetbrains.exposed.sql.transactions.transaction23import kotlin.random.nextInt24val directionSets = Arb.set(Arb.enum<Direction>(), 0..Direction.values().size)25val rotations = Exhaustive.ints(0..3).map { it.toShort() }26val invalidRotationValues = (Short.MIN_VALUE..Short.MAX_VALUE) - (0..3)27val invalidRotations = arbitrary(listOf(Short.MIN_VALUE, -1, 4, Short.MAX_VALUE), ShortShrinker) {28 it.random.nextInt(invalidRotationValues.indices).let { i -> invalidRotationValues[i] }.toShort()29}30class RoomsKtTest : DescribeSpec({31 useDatabase()32 describe("returnRoomToStack") {...
CategoryRepositoryCreateSpec.kt
Source:CategoryRepositoryCreateSpec.kt
1package com.gaveship.category.domain.model2import com.gaveship.category.Mock3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.ExpectSpec5import io.kotest.matchers.collections.shouldHaveSize6import io.kotest.matchers.collections.singleElement7import io.kotest.matchers.nulls.beNull8import io.kotest.matchers.shouldBe9import io.kotest.matchers.shouldHave10import io.kotest.matchers.shouldNot11import io.kotest.property.Arb12import io.kotest.property.arbitrary.chunked13import io.kotest.property.arbitrary.next14import io.kotest.property.arbitrary.single15import io.kotest.property.arbitrary.string16import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest17import org.springframework.data.jpa.repository.config.EnableJpaAuditing18import javax.validation.ConstraintViolation19import javax.validation.ConstraintViolationException20@EnableJpaAuditing21@DataJpaTest(22 showSql = true,23 properties = [24 "spring.flyway.enabled=false",25 "spring.jpa.hibernate.ddl-auto=create"26 ]27)28class CategoryRepositoryCreateSpec(29 private val categoryRepository: CategoryRepository30) : ExpectSpec() {...
VendedorTest.kt
Source:VendedorTest.kt
1package ar.edu.unahur.obj2.vendedores2import io.kotest.assertions.throwables.shouldThrowAny3import io.kotest.core.spec.style.DescribeSpec4import io.kotest.matchers.booleans.shouldBeFalse5import io.kotest.matchers.booleans.shouldBeTrue6import io.kotest.matchers.collections.shouldContain7import io.kotest.matchers.collections.shouldContainAll8import io.kotest.matchers.collections.shouldNotContain9import io.kotest.matchers.should10import io.kotest.matchers.shouldBe11class ComercioTest : DescribeSpec({12 val buenosAires = Provincia(15000000)13 val santaFe = Provincia(9000000)14 val cordoba = Provincia(12000000)15 val entreRios = Provincia(1500000)16 val chivilcoy = Ciudad(buenosAires)17 val bragado = Ciudad(buenosAires)18 val lobos = Ciudad(buenosAires)19 val pergamino = Ciudad(buenosAires)20 val zarate = Ciudad(buenosAires)21 val rosario = Ciudad(santaFe)22 val rafaela = Ciudad(santaFe)23 val sanFrancisco = Ciudad(cordoba)24 val diamante = Ciudad(entreRios)...
InMemoryHopRepositoryTest.kt
Source:InMemoryHopRepositoryTest.kt
...4import domain.hop.model.HopType5import domain.quantities.PercentRange6import domain.quantities.QuantityRange7import fixtures.sampleHop8import io.kotest.assertions.assertSoftly9import io.kotest.assertions.fail10import io.kotest.core.spec.style.ShouldSpec11import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder12import io.kotest.matchers.maps.shouldHaveSize13import io.kotest.matchers.nulls.shouldNotBeNull14import io.kotest.matchers.shouldBe15import io.kotest.matchers.string.shouldNotBeBlank16class InMemoryHopRepositoryTest : ShouldSpec({17 val repoUnderTest = InMemoryHopRepository()18 beforeEach {19 repoUnderTest.clear()20 }21 should("find hop by name") {22 // Givent23 repoUnderTest.save(sampleHop)24 repoUnderTest.save(sampleHop.copy(name = "Cascade", similarTo = listOf("Citra")))25 repoUnderTest.save(sampleHop.copy(name = "Chinook", similarTo = listOf("Cascade", "Citra", "Chinook")))26 // When & Then27 repoUnderTest.findByName("Citra").shouldNotBeNull().apply {28 assertSoftly {29 name shouldBe "Citra"...
CategoryRepositorySelectSpec.kt
Source:CategoryRepositorySelectSpec.kt
1package com.gaveship.category.domain.model2import com.gaveship.category.Mock3import io.kotest.core.spec.style.StringSpec4import io.kotest.matchers.collections.shouldHaveSize5import io.kotest.matchers.collections.singleElement6import io.kotest.matchers.nulls.beNull7import io.kotest.matchers.shouldBe8import io.kotest.matchers.shouldHave9import io.kotest.matchers.shouldNot10import io.kotest.property.arbitrary.chunked11import io.kotest.property.arbitrary.single12import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest13import org.springframework.data.jpa.repository.config.EnableJpaAuditing14@EnableJpaAuditing15@DataJpaTest(16 showSql = true,17 properties = [18 "spring.flyway.enabled=false",19 "spring.jpa.hibernate.ddl-auto=create"20 ]21)22class CategoryRepositorySelectSpec(23 private val categoryRepository: CategoryRepository24) : StringSpec() {25 init {26 "Root Categories ì¡°í ì±ê³µ Test" {...
ExampleSpec.kt
Source:ExampleSpec.kt
1package org.example2import arrow.core.Either3import arrow.optics.Traversal4import arrow.typeclasses.Monoid5import io.kotest.assertions.arrow.core.shouldBeRight6import io.kotest.core.spec.style.StringSpec7import io.kotest.matchers.shouldBe8import io.kotest.matchers.types.shouldBeTypeOf9import io.kotest.property.Arb10import io.kotest.property.arbitrary.int11import io.kotest.property.arbitrary.list12import io.kotest.property.arbitrary.map13import io.kotest.property.arbitrary.positiveInt14import io.kotest.property.arbitrary.string15import io.kotest.property.arrow.core.MonoidLaws16import io.kotest.property.arrow.core.either17import io.kotest.property.arrow.core.functionAToB18import io.kotest.property.arrow.laws.testLaws19import io.kotest.property.arrow.optics.TraversalLaws20import kotlin.jvm.JvmInline21class ExampleSpec : StringSpec({22 "true shouldBe true" {23 true shouldBe true24 }25 "exception should fail" {26 // throw RuntimeException("Boom2!")27 }28 "kotest arrow extension use-cases" {29 // smart-cast abilities for arrow types30 Either.Right("HI").shouldBeRight().shouldBeTypeOf<String>()31 }32 // utilise builtin or costume Laws with Generators to verify behavior33 testLaws(34 MonoidLaws.laws(Monoid.list(), Arb.list(Arb.string())),35 MonoidLaws.laws(Monoid.numbers(), Arb.numbers())36 )37 // optics Laws from arrow38 testLaws(39 TraversalLaws.laws(40 traversal = Traversal.either(),41 aGen = Arb.either(Arb.string(), Arb.int()),42 bGen = Arb.int(),43 funcGen = Arb.functionAToB(Arb.int()),44 )45 )46})47fun Arb.Companion.numbers(): Arb<Numbers> =48 Arb.positiveInt().map { it.toNumber() }49fun Int.toNumber(): Numbers =50 if (this <= 0) Zero else Suc(minus(1).toNumber())51// natural numbers form a monoid52fun Monoid.Companion.numbers(): Monoid<Numbers> =...
FunSpecSimpleTest.kt
Source:FunSpecSimpleTest.kt
1package com.kotlinspring.styles2import io.kotest.assertions.json.shouldEqualJson3import io.kotest.assertions.json.shouldNotEqualJson4import io.kotest.core.spec.style.FunSpec5import io.kotest.matchers.should6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.endWith8import io.kotest.matchers.string.shouldContain9import io.kotest.matchers.string.startWith10class FunSpecSimpleTest : FunSpec({11 test("name of tester should return the correct length") {12 val nameTester = "Matheus Marin"13 nameTester.shouldContain("Matheus")14 nameTester.length shouldBe 1315 nameTester should startWith("Matheus")16 nameTester should endWith("Marin")17 }18 test("a json with a developer should be valid") {19 val json = """ { "age" : 23, "name": "matheus", "location": "sao paulo" } """20 json.shouldEqualJson(returnJsonOfAValidDev())21 }22 test("a json with a PO should be invalid") {23 val json = """ { "age" : 45, "name": "robert", "location": "rio de janeiro" } """24 json.shouldNotEqualJson(returnJsonOfAValidDev())25 }26}) {27 companion object {28 fun returnJsonOfAValidDev() : String{29 return """ { "age" : 23, "name": "matheus", "location": "sao paulo" } """30 }31 }32}...
test
Using AI Code Generation
1 fun `should return a list of all the books`() {2 val book1 = Book("1", "Book 1", "Author 1", 100)3 val book2 = Book("2", "Book 2", "Author 2", 200)4 val book3 = Book("3", "Book 3", "Author 3", 300)5 val book4 = Book("4", "Book 4", "Author 1", 400)6 val book5 = Book("5", "Book 5", "Author 2", 500)7 val book6 = Book("6", "Book 6", "Author 3", 600)8 val book7 = Book("7", "Book 7", "Author 1", 700)9 val book8 = Book("8", "Book 8", "Author 2", 800)10 val book9 = Book("9", "Book 9", "Author 3", 900)11 val book10 = Book("10", "Book 10", "Author 1", 1000)12 val book11 = Book("11", "Book 11", "Author 2", 1100)13 val book12 = Book("12", "Book 12", "Author 3", 1200)14 val book13 = Book("13", "Book 13", "Author 1", 1300)15 val book14 = Book("14", "Book 14", "Author 2", 1400)16 val book15 = Book("15", "Book 15", "Author 3", 1500)17 val books = listOf(book1, book2, book3, book4, book5, book6, book7, book8, book9, book10, book11, book12, book13, book14, book15)18 val result = bookService.findAll()19 }
test
Using AI Code Generation
1import io.kotest.matchers.shouldBe2class Test {3 fun test() {4 val list = listOf(1, 2, 3, 4, 5)5 }6}7import io.kotest.core.spec.style.FunSpec8class Test : FunSpec({9 test("test") {10 val list = listOf(1, 2, 3, 4, 5)11 }12})13import io.kotest.core.spec.style.StringSpec14class Test : StringSpec({15 "test" {16 val list = listOf(1, 2, 3, 4, 5)17 }18})19import io.kotest.core.spec.style.WordSpec20class Test : WordSpec({21 "test" should {22 "test" {23 val list = listOf(1, 2, 3, 4, 5)24 }25 }26})27import io.kotest.core.spec.style.FreeSpec28class Test : FreeSpec({29 "test" - {30 "test" {31 val list = listOf(1, 2, 3, 4, 5)32 }33 }34})35import io.kotest.core.spec.style.ShouldSpec36class Test : ShouldSpec({37 "test" {38 should("test") {39 val list = listOf(1, 2, 3, 4, 5)40 }41 }42})43import io.kotest.core.spec.style.ExpectSpec44class Test : ExpectSpec({45 context("test") {46 expect("test") {47 val list = listOf(1, 2, 3, 4, 5)48 }49 }50})
test
Using AI Code Generation
1class StringTest : ShouldSpec() {2 init {3 "A String" {4 "should have length" {5 }6 "should start with s" {7 "sammy" should startWith("s")8 }9 }10 }11}12class StringTest2 : ShouldSpec() {13 init {14 "A String" {15 "should have length" {16 }17 "should start with s" {18 "sammy" should startWith("s")19 }20 }21 }22}23class StringTest3 : ShouldSpec() {24 init {25 "A String" {26 "should have length" {27 }28 "should start with s" {29 "sammy" should startWith("s")30 }31 }32 }33}34class StringTest4 : ShouldSpec() {35 init {36 "A String" {37 "should have length" {38 }39 "should start with s" {40 "sammy" should startWith("s")41 }42 }43 }44}45class StringTest5 : ShouldSpec() {46 init {47 "A String" {48 "should have length" {49 }50 "should start with s" {51 "sammy" should startWith("s")52 }53 }54 }55}56class StringTest6 : ShouldSpec() {57 init {58 "A String" {59 "should have length" {60 }61 "should start with s" {62 "sammy" should startWith("s")63 }64 }65 }66}67class StringTest7 : ShouldSpec() {68 init {69 "A String" {70 "should have length" {
test
Using AI Code Generation
1 val result = add(1, 2)2 result.shouldBe(3)3 }4 fun `should add two numbers using result matcher`() {5 val result = add(1, 2)6 }7 fun `should add two numbers using matchers`() {8 val result = add(1, 2)9 }10 fun `should add two numbers using matchers with error message`() {11 val result = add(1, 2)12 }13 fun `should add two numbers using matchers with error message and lambda`() {14 val result = add(1, 2)15 }16 fun `should add two numbers using matchers with error message and lambda and string interpolation`() {17 val result = add(1, 2)18 }19 fun `should add two numbers using matchers with error message and lambda and string interpolation and string template`() {20 val result = add(1, 2)
test
Using AI Code Generation
1 test("test of function") {2 val result = function()3 result.shouldBe("Hello World")4 }5}6fun function(): String {7}
test
Using AI Code Generation
1class CalculatorUnitTest {2 fun addTwoNumbers() {3 val calculator = Calculator()4 calculator.add(2, 2) shouldBe 45 }6 fun subtractTwoNumbers() {7 val calculator = Calculator()8 calculator.subtract(4, 2) shouldBe 29 }10 fun multiplyTwoNumbers() {11 val calculator = Calculator()12 calculator.multiply(4, 2) shouldBe 813 }14 fun divideTwoNumbers() {15 val calculator = Calculator()16 calculator.divide(4, 2) shouldBe 217 }18 fun divideTwoNumbersWithDecimalPlaces() {19 val calculator = Calculator()20 calculator.divide(4, 3) shouldBe 1.333333333333333321 }22 fun divideTwoNumbersWithDecimalPlacesAndRounding() {23 val calculator = Calculator()24 calculator.divide(4, 3, 2) shouldBe 1.3325 }26 fun divideTwoNumbersWithDecimalPlacesAndRoundingWithRoundingDown() {27 val calculator = Calculator()
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!!