Best Kotest code snippet using io.kotest.matchers.collections.contain.Array.shouldContain
RandomServiceTest.kt
Source:RandomServiceTest.kt
1package io.github.serpro69.kfaker2import io.kotest.assertions.assertSoftly3import io.kotest.assertions.throwables.shouldThrow4import io.kotest.core.spec.style.DescribeSpec5import io.kotest.matchers.collections.shouldContain6import io.kotest.matchers.shouldBe7import io.kotest.matchers.string.shouldContain8import java.util.*9internal class RandomServiceTest : DescribeSpec({10 describe("RandomService instance") {11 val randomService = RandomService(Random())12 context("calling nextInt(min, max)") {13 val values = List(100) { randomService.nextInt(6..8) }14 it("return value should be within specified range") {15 values.all { it in 6..8 } shouldBe true16 }17 }18 context("calling nextInt(intRange)") {19 val values = List(100) { randomService.nextInt(3..9) }20 it("return value should be within specified range") {21 values.all { it in 3..9 } shouldBe true22 }23 }24 context("calling randomValue<T>(list)") {25 context("list is not empty") {26 val values = List(100) { randomService.nextInt(3..9) }27 val value = randomService.randomValue(values)28 it("return value should be in the list") {29 values shouldContain value30 }31 }32 context("list is empty") {33 val values = listOf<String>()34 it("exception is thrown") {35 shouldThrow<IllegalArgumentException> {36 randomService.randomValue(values)37 }38 }39 }40 context("list contains nulls") {41 val values = listOf(1, 2, 3, null).filter { it == null }42 val value = randomService.randomValue(values)43 it("return value should be in the list") {44 assertSoftly {45 values shouldContain value46 value shouldBe null47 }48 }49 }50 }51 context("calling randomValue<T>(array)") {52 context("array is not empty") {53 val values = Array(100) { randomService.nextInt(3..9) }54 val value = randomService.randomValue(values)55 it("return value should be in the array") {56 values shouldContain value57 }58 }59 context("array is empty") {60 val values = arrayOf<String>()61 it("exception is thrown") {62 shouldThrow<IllegalArgumentException> {63 randomService.randomValue(values)64 }65 }66 }67 context("array contains nulls") {68 val values = arrayOf(1, 2, 3, null).filter { it == null }69 val value = randomService.randomValue(values)70 it("return value should be in the array") {71 assertSoftly {72 values shouldContain value73 value shouldBe null74 }75 }76 }77 }78 context("calling nextChar()") {79 val source = "qwertyuiopasdfghjklzxcvbnm"80 context("upperCase is true") {81 it("random upper-case letter is generated") {82 val letter = randomService.nextLetter(true).toString()83 source.toUpperCase() shouldContain letter84 }85 }86 context("upperCase is false") {87 it("random lower-case letter is generated") {88 val letter = randomService.nextLetter(false).toString()89 source shouldContain letter90 }91 }92 }93 }94})...
FileSystemServiceImplTest.kt
Source:FileSystemServiceImplTest.kt
1package org.factcast.schema.registry.cli.fs2import com.fasterxml.jackson.databind.JsonNode3import io.kotest.core.spec.style.StringSpec4import io.kotest.core.test.TestCase5import io.kotest.core.test.TestResult6import io.kotest.matchers.collections.shouldContain7import io.kotest.matchers.collections.shouldHaveSize8import io.kotest.matchers.shouldBe9import io.kotest.matchers.string.shouldContain10import io.kotest.matchers.string.shouldNotContain11import io.kotest.matchers.types.shouldBeInstanceOf12import org.factcast.schema.registry.cli.fixture13import java.nio.file.Files14import java.nio.file.Paths15class FileSystemServiceImplTest : StringSpec() {16 var tmp = Files.createTempDirectory("fc-test")17 val uut = FileSystemServiceImpl()18 override fun afterTest(testCase: TestCase, result: TestResult) {19 try {20 Files.delete(tmp)21 } catch (e: Exception) {22 } finally {23 tmp = Files.createTempDirectory("fx-test")24 }25 }26 init {27 "exists" {28 uut.exists(fixture("schema.json")) shouldBe true29 uut.exists(fixture("nope.json")) shouldBe false30 }31 "listDirectories" {32 uut.listDirectories(fixture("")) shouldContain fixture("sample-folder")33 uut.listDirectories(fixture("sample-folder")) shouldHaveSize 034 }35 "listFiles" {36 val files = uut.listFiles(fixture(""))37 files shouldHaveSize 138 files shouldContain fixture("schema.json")39 }40 "ensureDirectories" {41 val outputPath = Paths.get(tmp.toString(), "foo")42 uut.ensureDirectories(outputPath)43 uut.exists(outputPath) shouldBe true44 }45 "writeToFile" {46 val outputPath = Paths.get(tmp.toString(), "test.txt")47 uut.writeToFile(outputPath.toFile(), "bar")48 uut.exists(outputPath) shouldBe true49 }50 "readToString" {51 uut.readToString(fixture("schema.json").toFile()) shouldContain "firstName"52 }53 "readToStrings" {54 val output = uut.readToStrings(fixture("schema.json").toFile())55 output[1] shouldContain "additionalProperties"56 output[8] shouldContain "required"57 }58 "copyFile" {59 val outputPath = Paths.get(tmp.toString(), "schema.json")60 uut.copyFile(fixture("schema.json").toFile(), outputPath.toFile())61 uut.exists(outputPath)62 }63 "readToJsonNode" {64 uut.readToJsonNode(fixture("schema.json")).shouldBeInstanceOf<JsonNode>()65 uut.readToJsonNode(fixture("nope.json")) shouldBe null66 }67 "deleteDirectory" {68 uut.exists(tmp) shouldBe true69 uut.deleteDirectory(tmp)70 uut.exists(tmp) shouldBe false71 }72 "readToBytes" {73 val exampleFile = fixture("schema.json")74 uut.readToBytes(exampleFile) shouldBe uut.readToString(exampleFile.toFile()).toByteArray()75 }76 "copyDirectory" {77 val outputPath = Paths.get(tmp.toString(), "foo")78 uut.exists(outputPath) shouldBe false79 uut.copyDirectory(fixture(""), outputPath)80 uut.exists(outputPath) shouldBe true81 }82 "copyFilteredJson" {83 val outputPath = Paths.get(tmp.toString(), "test.txt")84 uut.copyFilteredJson(85 fixture("schema.json").toFile(),86 outputPath.toFile(),87 setOf("title")88 )89 uut.exists(outputPath) shouldBe true90 uut.readToString(outputPath.toFile()) shouldNotContain "title"91 }92 }93}...
DbServiceTest.kt
Source:DbServiceTest.kt
1package de.obscure.web2import arrow.core.nonEmptyListOf3import de.obscure.web.db.entity.StatisticEntity4import de.obscure.web.db.service.DbService5import de.obscure.web.domain.CameraType6import de.obscure.web.domain.Image7import io.kotest.core.spec.style.StringSpec8import io.kotest.core.test.TestCase9import io.kotest.matchers.collections.shouldBeEmpty10import io.kotest.matchers.collections.shouldContain11import io.kotest.matchers.collections.shouldContainExactly12import io.kotest.matchers.collections.shouldHaveSize13import io.kotest.matchers.nulls.shouldNotBeNull14import io.kotest.matchers.shouldBe15import io.micronaut.runtime.EmbeddedApplication16import io.micronaut.test.extensions.kotest.annotation.MicronautTest17import org.flywaydb.core.Flyway18import java.time.Instant19@MicronautTest20class DbServiceTest(21 private val dbService: DbService,22 private val flyway: Flyway) : StringSpec({23 val imageEntity = { s: StatisticEntity -> Image(null, CameraType.WEBCAM_IBERG, 0, 0, 0, emptyArray()).toImageEntity(s) }24 val statisticEntity = StatisticEntity(25 null,26 Instant.now(),27 20.0f,28 45.0f,29 1000.0f,30 "steigend",31 30.0f,32 40.0f,33 0.0f,34 1.2f,35 false36 )37 "findAllStatistics() should return all stored statistics and images" {38 val statisticEntity1 = statisticEntity.copy()39 dbService.saveStatistic(statisticEntity1, nonEmptyListOf(imageEntity(statisticEntity)))40 val loadedStatistics = dbService.findAllStatistics()41 loadedStatistics.shouldContain(statisticEntity1)42 val loadedImage = dbService.findImageByStatisticIdAndCamType(loadedStatistics.first().id!!, CameraType.WEBCAM_IBERG)43 loadedImage.shouldNotBeNull()44 }45 "findLastStatistic() should return statistic wih the highest id" {46 val currentTime = Instant.now()47 val statisticEntity1 = statisticEntity.copy(timestamp = currentTime)48 val statisticEntity2 = statisticEntity.copy(timestamp = currentTime.plusSeconds(1))49 dbService.saveStatistic(statisticEntity1, nonEmptyListOf(imageEntity(statisticEntity1)))50 dbService.saveStatistic(statisticEntity2, nonEmptyListOf(imageEntity(statisticEntity2)))51 val loadedStatistic = dbService.findLastStatistic()52 loadedStatistic?.id.shouldBe(2L)53 loadedStatistic?.timestamp.shouldBe(currentTime.plusSeconds(1))54 }55 "findByTimestampAfter() should return only entries after the given instant time" {56 val currentTime = Instant.now()57 val statisticEntity1 = statisticEntity.copy()58 val statisticEntity2 = statisticEntity.copy(timestamp = currentTime.plusSeconds(1))59 val statisticEntity3 = statisticEntity.copy(timestamp = currentTime.plusSeconds(2))60 //store statistics61 listOf(statisticEntity1, statisticEntity2, statisticEntity3).forEach {62 dbService.saveStatistic(it, nonEmptyListOf(imageEntity(it)))63 }64 dbService.findByTimestampAfter(currentTime)65 .shouldHaveSize(2)66 .shouldContainExactly(statisticEntity2, statisticEntity3)67 dbService.findByTimestampAfter(currentTime.plusSeconds(10))68 .shouldBeEmpty()69 }70}) {71 override fun beforeEach(testCase: TestCase) {72 flyway.clean()73 flyway.migrate()74 }75}...
HeadersSpec.kt
Source:HeadersSpec.kt
1package io.micronaut.nats.docs.headers2import io.kotest.assertions.timing.eventually3import io.kotest.matchers.collections.shouldContain4import io.kotest.matchers.shouldBe5import io.micronaut.nats.AbstractNatsTest6import io.nats.client.impl.Headers7import kotlin.time.Duration8import kotlin.time.ExperimentalTime9@OptIn(ExperimentalTime::class)10class HeadersSpec : AbstractNatsTest({11 val specName = javaClass.simpleName12 given("A basic producer and consumer") {13 val ctx = startContext(specName)14 `when`("The messages are published") {15 val productListener = ctx.getBean(ProductListener::class.java)16 // tag::producer[]17 val productClient = ctx.getBean(ProductClient::class.java)18 productClient.send("body".toByteArray());19 productClient.send("medium", 20L, "body2".toByteArray());20 productClient.send(null, 30L, "body3".toByteArray());21 val headers = Headers()22 headers.put("productSize", "large")23 headers.put("x-product-count", "40")24 productClient.send("body4".toByteArray(), headers);25 productClient.send("body5".toByteArray(), listOf("xtra-small", "xtra-large"));26 // end::producer[]27 then("The messages are received") {28 eventually(Duration.seconds(10)) {29 productListener.messageProperties.size shouldBe 630 productListener.messageProperties shouldContain "true|10|small"31 productListener.messageProperties shouldContain "true|20|medium"32 productListener.messageProperties shouldContain "true|30|medium"33 productListener.messageProperties shouldContain "true|40|large"34 productListener.messageProperties shouldContain "true|20|xtra-small"35 productListener.messageProperties shouldContain "true|20|xtra-large"36 }37 }38 }39 ctx.stop()40 }41})...
EncodingHuffmanTreeTests.kt
Source:EncodingHuffmanTreeTests.kt
1package info.spadger.datastructures.huffman2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.collections.shouldContain4import io.kotest.matchers.shouldBe5import io.kotest.matchers.types.shouldBeInstanceOf6@kotlin.ExperimentalUnsignedTypes7class EncodingHuffmanTreeTests : StringSpec({8 "Initial state should be built correctly from input bytes" {9 val input = byteArrayOf(3, 0, 0, 5, 5, 5, 0, 0, 0, 1, 2, 0, 5, 5, 2, 3, 3).asUByteArray()10 val result = EncodingHuffmanTree.createInitialHistogram(input)11 result.size shouldBe 512 result shouldContain SingleValue(0.toUByte())13 result shouldContain SingleValue(5.toUByte())14 result shouldContain SingleValue(3.toUByte())15 result shouldContain SingleValue(2.toUByte())16 result shouldContain SingleValue(1.toUByte())17 }18 "An empty byte-array yields an empty set of codes" {19 val input = byteArrayOf()20 val sut = EncodingHuffmanTree.fromUncompressedData(input)21 sut.codeCount shouldBe 022 sut.shouldBeInstanceOf<EmptyEncodingHuffmanTree>()23 }24 "A byte-array with only a single specific byte yields the code 0" {25 val input = byteArrayOf(100, 100, 100, 100, 100)26 val sut = EncodingHuffmanTree.fromUncompressedData(input)27 sut.codeCount shouldBe 128 sut.encode(100.toUByte()) shouldBe listOf(false)29 }30 "A multiple bytes yields a valid tree" {31 val input = byteArrayOf(100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 1, 2, 2)32 val sut = EncodingHuffmanTree.fromUncompressedData(input)33 sut.codeCount shouldBe 334 sut.encode(100.toUByte()) shouldBe listOf(false)35 sut.encode(2.toUByte()) shouldBe listOf(true, false)36 sut.encode(1.toUByte()) shouldBe listOf(true, true)37 }38})...
_001_FindMultInArrayTest.kt
Source:_001_FindMultInArrayTest.kt
...19 it shouldBeGreaterThanOrEqual 020 }21 val resultArray = _001_FindMultInArray.findMult(array)22 resultArray shouldNotContain 123 resultArray shouldContain 224 resultArray shouldHaveSize 325 val testList: List<Int> = listOf(2, 3, 5)26 resultArray shouldContainAll testList27 }28 @Test29 fun findMultTestContainNull() {30 val array = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8).toIntArray()31 array.forEach {32 it shouldBeLessThan array.size33 it shouldBeGreaterThanOrEqual 034 }35 _001_FindMultInArray.findMult(array) shouldHaveSize 036 }37}...
PropertiesSpec.kt
Source:PropertiesSpec.kt
1package io.micronaut.mqtt.docs.properties2import io.kotest.assertions.timing.eventually3import io.kotest.matchers.collections.shouldContain4import io.kotest.matchers.shouldBe5import io.micronaut.mqtt.AbstractMqttKotest6import org.opentest4j.AssertionFailedError7import kotlin.time.DurationUnit8import kotlin.time.ExperimentalTime9import kotlin.time.toDuration10@ExperimentalTime11class PropertiesSpec : AbstractMqttKotest({12 val specName = javaClass.simpleName13 given("publishing and receiving properties") {14 val ctx = startContext(specName)15 `when`("messages with properties are sent") {16 // tag::producer[]17 val productClient = ctx.getBean(ProductClient::class.java)18 productClient.send("body".toByteArray())19 productClient.send("guest", "text/html", "body2".toByteArray())20 productClient.send("guest", null, "body3".toByteArray())21 // end::producer[]22 then("the messages are received") {23 val productListener = ctx.getBean(ProductListener::class.java)24 eventually(10.toDuration(DurationUnit.SECONDS), AssertionFailedError::class) {25 productListener.messageProperties.size shouldBe 326 productListener.messageProperties shouldContain "guest|application/json|myApp"27 productListener.messageProperties shouldContain "guest|text/html|myApp"28 productListener.messageProperties shouldContain "guest|null|myApp"29 }30 }31 }32 ctx.stop()33 }34})...
BindingSpec.kt
Source:BindingSpec.kt
1package io.micronaut.mqtt.docs.parameters2import io.kotest.assertions.timing.eventually3import io.kotest.matchers.collections.shouldContain4import io.kotest.matchers.shouldBe5import io.micronaut.mqtt.AbstractMqttKotest6import org.opentest4j.AssertionFailedError7import kotlin.time.DurationUnit8import kotlin.time.ExperimentalTime9import kotlin.time.toDuration10@ExperimentalTime11class BindingSpec: AbstractMqttKotest({12 val specName = javaClass.simpleName13 given("A basic producer and consumer") {14 val ctx = startContext(specName)15 `when`("The messages are published") {16 val productListener = ctx.getBean(ProductListener::class.java)17 // tag::producer[]18 val productClient = ctx.getBean(ProductClient::class.java)19 productClient.send("message body".toByteArray())20 productClient.send("product", "message body2".toByteArray())21 // end::producer[]22 then("The messages are received") {23 eventually(10.toDuration(DurationUnit.SECONDS), AssertionFailedError::class) {24 productListener.messageLengths.size shouldBe 225 productListener.messageLengths shouldContain 1226 productListener.messageLengths shouldContain 1327 }28 }29 }30 ctx.stop()31 }32})...
Array.shouldContain
Using AI Code Generation
1 import io.kotest.matchers.collections.contain2 import io.kotest.matchers.should3 import io.kotest.matchers.shouldBe4 import io.kotest.matchers.shouldContain5 import io.kotest.matchers.shouldNotBe6 import org.junit.jupiter.api.Test7 import org.junit.jupiter.api.assertThrows8 import org.junit.jupiter.api.fail9 class KotlinTest {10 fun test() {11 val actual = listOf(1, 2, 3)12 actual.shouldContain(2)13 actual should contain(2)
Array.shouldContain
Using AI Code Generation
1val array = arrayOf(1, 2, 3)2val array = arrayOf(1, 2, 3)3val array = arrayOf(1, 2, 3)4array shouldContainAll listOf(1, 2)5val array = arrayOf(1, 2, 3)6array shouldNotContainAll listOf(1, 3)7val array = arrayOf(1, 2, 3)8array shouldContainAny listOf(1, 3)9val array = arrayOf(1, 2, 3)10array shouldNotContainAny listOf(4, 5)11val array = arrayOf(1, 2, 3)12array shouldContainInOrder listOf(1, 2)13val array = arrayOf(1, 2, 3)14array shouldNotContainInOrder listOf(1, 3)15val array = arrayOf(1, 2, 3)16array shouldContainInOrderOnly listOf(1, 2, 3)17val array = arrayOf(1, 2, 3)18array shouldNotContainInOrderOnly listOf(1, 3)19val array = arrayOf(1, 2, 3)20array shouldContainExactly listOf(1, 2, 3)
Array.shouldContain
Using AI Code Generation
1 import io.kotest.matchers.collections.contain2 import io.kotest.matchers.should3 import io.kotest.matchers.shouldBe4 import org.junit.jupiter.api.Test5 import org.junit.jupiter.api.assertThrows6 import java.time.LocalDate7 import java.time.Month8 import java.time.Period9 import java.time.format.DateTimeFormatter10 import java.time.format.DateTimeParseException11 class PersonTest {12 fun `should return person's age in years`() {13 val person = Person("John", "Doe", LocalDate.of(1980, Month.JANUARY, 1))14 }15 fun `should return person's age in years when born in leap year`() {16 val person = Person("John", "Doe", LocalDate.of(1984, Month.FEBRUARY, 29))17 }18 fun `should throw exception when date of birth is in future`() {19 val person = Person("John", "Doe", LocalDate.of(2020, Month.JANUARY, 1))20 assertThrows<DateTimeParseException> { person.age }21 }22 fun `should return person's full name`() {23 val person = Person("John", "Doe", LocalDate.of(1980, Month.JANUARY, 1))24 person.fullName() shouldBe "John Doe"25 }26 fun `should return person's initials`() {27 val person = Person("John", "Doe", LocalDate.of(1980, Month.JANUARY, 1))28 person.initials() shouldBe "JD"29 }30 fun `should return person's formatted date of birth`() {31 val person = Person("John", "Doe", LocalDate.of(1980, Month.JANUARY, 1))32 person.formattedDateOfBirth() shouldBe "01/01/1980"33 }34 fun `should return person's formatted date of birth when born in leap year`() {35 val person = Person("John", "Doe", LocalDate.of(1984, Month.FEBRUARY, 29))36 person.formattedDateOfBirth() shouldBe "29/02/1984"37 }
Array.shouldContain
Using AI Code Generation
1assertThat(array).shouldContain(1, 2, 3)2assertThat(array).shouldNotContain(1, 2, 3)3assertThat(array).shouldBeEmpty()4assertThat(array).shouldNotBeEmpty()5assertThat(array).shouldBeSorted()6assertThat(array).shouldNotBeSorted()7assertThat(array).shouldBeSortedDescending()8assertThat(array).shouldNotBeSortedDescending()9assertThat(array).shouldBeSortedWith(Comparator { o1, o2 -> o1.compareTo(o2) })10assertThat(array).shouldNotBeSortedWith(Comparator { o1, o2 -> o1.compareTo(o2) })11assertThat(array).shouldBeIn(1, 2, 3)12assertThat(array).shouldNotBeIn(1, 2, 3)13assertThat(array).shouldBeSubsetOf(1, 2, 3)14assertThat(array).shouldNotBeSubsetOf(1, 2, 3)
Array.shouldContain
Using AI Code Generation
1val array = arrayOf ( "a" , "b" , "c" )2val array = arrayOf ( "a" , "b" , "c" )3array shouldContainAll listOf ( "a" , "c" )4array shouldNotContainAll listOf ( "a" , "d" )5val array = arrayOf ( )6val array = arrayOf ( 1 , 2 , 3 )7val array = arrayOf ( 1 , 2 , 3 )8array shouldBeSortedWith compareBy ( { it } )9array shouldNotBeSortedWith compareBy ( { it } )10val array = arrayOf ( "a" , "b" , "c" )11array shouldBeSortedBy { it }12array shouldNotBeSortedBy { it }13val array = arrayOf ( "a" , "b" , "c" )14array shouldBeSortedByDescending { it }15array shouldNotBeSortedByDescending { it }16val array = arrayOf ( "a" , "b" , "c" )17array shouldBeSortedBy { it }18array shouldNotBeSortedBy { it }19val array = arrayOf ( "a" , "b" , "c" )20array shouldBeSortedByDescending { it }21array shouldNotBeSortedByDescending { it }22val array = arrayOf ( "a" , "b" , "c" )
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!!