Best Kotest code snippet using io.kotest.matchers.collections.size.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})...
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() {...
MultimapTests.kt
Source:MultimapTests.kt
1package com.adidas.mvi2import io.kotest.assertions.assertSoftly3import io.kotest.core.spec.IsolationMode4import io.kotest.core.spec.style.BehaviorSpec5import io.kotest.matchers.collections.shouldBeEmpty6import io.kotest.matchers.collections.shouldContain7import io.kotest.matchers.collections.shouldHaveSize8import io.kotest.matchers.collections.shouldNotContain9import io.kotest.matchers.shouldBe10internal class MultimapTests : BehaviorSpec({11 isolationMode = IsolationMode.InstancePerLeaf12 given("An empty multimap") {13 val multimap = Multimap<String, Int>()14 `when`("I put a value") {15 val entry = multimap.put("Test", 1)16 then("The value should be returned") {17 entry shouldBe MultimapEntry("Test", 1)18 }19 then("The value should be in the map") {20 assertSoftly(multimap["Test"]) {21 shouldHaveSize(1)22 shouldContain(MultimapEntry("Test", 1))23 }...
UserApiV1Test.kt
Source:UserApiV1Test.kt
1package io.andrewohara.tabbychat.protocol.v1.api2import dev.forkhandles.result4k.valueOrNull3import dev.mrbergin.kotest.result4k.shouldBeFailure4import dev.mrbergin.kotest.result4k.shouldBeSuccess5import io.andrewohara.tabbychat.*6import io.andrewohara.tabbychat.auth.Realm7import io.andrewohara.tabbychat.contacts.TokenData8import io.andrewohara.tabbychat.protocol.v1.client.UserClientV19import io.andrewohara.tabbychat.protocol.v1.toDtoV110import io.andrewohara.utils.jdk.minus11import io.kotest.matchers.collections.shouldBeEmpty12import io.kotest.matchers.collections.shouldContainExactly13import io.kotest.matchers.collections.shouldHaveSize14import io.kotest.matchers.nulls.shouldBeNull15import io.kotest.matchers.shouldBe16import org.http4k.core.Uri17import org.junit.jupiter.api.Test18import java.time.Duration19class UserApiV1Test {20 private val driver = TestDriver()21 private val provider = driver.createProvider(Realm(Uri.of("http://tabby.chat")))22 private val self = provider.createUser("self")23 private val selfToken: TokenData = provider.service.createAccessToken(self.id).valueOrNull()!!24 private val contact = provider.createUser("contact").also {25 driver.givenContacts(self, it)26 }27 private val other = provider.createUser("other")28 private val client = UserClientV1(selfToken.toDtoV1(), provider)29 @Test...
Kotest.kt
Source:Kotest.kt
1package io.kotest.plugin.pitest2import io.kotest.core.spec.style.FunSpec3import io.kotest.core.spec.style.StringSpec4import io.kotest.core.spec.style.WordSpec5import io.kotest.matchers.collections.shouldBeEmpty6import io.kotest.matchers.collections.shouldHaveSize7import io.kotest.matchers.shouldBe8class Kotest : FunSpec() {9 init {10 test("StringSpecs") {11 val resultCollector = findTestsIn(StringSpecs::class.java)12 resultCollector.skipped.shouldBeEmpty()13 resultCollector.started.shouldHaveSize(2)14 resultCollector.ended.shouldHaveSize(2)15 resultCollector.failures.shouldHaveSize(1)16 }17 test("FunSpecs") {18 val resultCollector = findTestsIn(FunSpecs::class.java)19 resultCollector.skipped.shouldBeEmpty()20 resultCollector.started.shouldHaveSize(2)21 resultCollector.ended.shouldHaveSize(2)22 resultCollector.failures.shouldHaveSize(1)23 }24 test("WordSpecs") {25 val resultCollector = findTestsIn(WordSpecs::class.java)26 resultCollector.skipped.shouldBeEmpty()27 resultCollector.started.shouldHaveSize(7)28 resultCollector.ended.shouldHaveSize(7)29 resultCollector.failures.shouldHaveSize(2)30 }31 }32 private fun findTestsIn(clazz: Class<*>): TestResultCollector {33 val resultCollector = TestResultCollector()34 KotestUnitFinder().findTestUnits(clazz)35 .stream()36 .forEach { testUnit -> testUnit.execute(resultCollector) }37 return resultCollector38 }39}40private class FunSpecs : FunSpec() {41 init {42 test("passing test") { 1 shouldBe 1 }43 test("failing test") { 1 shouldBe 2 }44 }45}46private class StringSpecs : StringSpec() {47 init {48 "passing test" { 1 shouldBe 1 }49 "failing test" { 1 shouldBe 2 }50 }51}52private class WordSpecs : WordSpec() {53 init {54 "should container" should {55 "passing test" { 1 shouldBe 1 }56 "failing test" { 1 shouldBe 2 }57 }58 "when container" `when` {59 "nested should container" should {60 "passing test" { 1 shouldBe 1 }61 "failing test" { 1 shouldBe 2 }62 }63 }64 }65}...
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" {...
KoTestTest.kt
Source:KoTestTest.kt
1package com.example.testingcomparison2import io.kotest.assertions.assertSoftly3import io.kotest.matchers.Matcher4import io.kotest.matchers.MatcherResult5import io.kotest.matchers.collections.shouldContain6import io.kotest.matchers.collections.shouldHaveSize7import io.kotest.matchers.collections.shouldNotContain8import io.kotest.matchers.should9import io.kotest.matchers.types.shouldBeInstanceOf10import org.junit.Test11class KoTestTest {12 private val animals = listOf("Rex", "Caramel", "Joe", "Anna")13 @Test14 fun kotest() {15 animals should containPalyndrom()16 animals17 .shouldBeInstanceOf<List<String>>()18 .shouldContain("Rex") // Doesn't let me chain here19 animals.shouldNotContain("Snow") // Doesn't let me chain here20 animals.shouldHaveSize(3)21 }22 @Test23 fun kotestSoftList() {24 assertSoftly {25 animals.shouldHaveSize(2)26 animals27 .shouldBeInstanceOf<List<String>>()28 .shouldContain("Rex") // Doesn't let me chain here29 animals.shouldNotContain("Snow") // Doesn't let me chain here30 animals.shouldHaveSize(3)31 }32 }33 fun containPalyndrom() = object : Matcher<List<String>> {34 override fun test(value: List<String>): MatcherResult {35 return MatcherResult(36 value.any { it.reversed().equals(it, ignoreCase = true) },37 "List should contain palindrome",38 "List shouldn't contain palindrome"39 )40 }41 }42}...
TodoListControllerTest.kt
Source:TodoListControllerTest.kt
1package com.example.todo.controller2import com.example.todo.model.Todo3import com.example.todo.repository.TodoRepository4import io.kotest.core.spec.style.DescribeSpec5import io.kotest.matchers.collections.shouldContainAll6import io.kotest.matchers.collections.shouldHaveSize7import io.mockk.every8import io.mockk.mockk9import io.mockk.unmockkAll10import io.mockk.verify11class TodoListControllerTest : DescribeSpec({12 lateinit var mockTodoRepository: TodoRepository13 lateinit var todoController: TodoListController14 beforeTest {15 mockTodoRepository = mockk()16 todoController = TodoListController(mockTodoRepository)17 }18 describe("Test TODO controller endpoints") {19 it("should get all the TODOs") {20 val listOfExpectedTodos = listOf(Todo(1, "Read a book", false), Todo(2, "Hit the gym", true))...
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!!