Best Kotest code snippet using io.kotest.common.intellij
CUtil.kt
Source:CUtil.kt  
...11import com.tschuchort.compiletesting.SourceFileAccessor12import io.kotest.matchers.shouldBe13import io.kotest.matchers.string.shouldContain14import io.kotest.matchers.string.shouldNotContain15import org.intellij.lang.annotations.Language16import org.jetbrains.kotlin.name.FqName17import java.net.URLClassLoader18import java.nio.file.Files19import kotlin.reflect.KClass20var fileIndex = 021fun source(22  @Language("kotlin") source: String,23  name: String = "File${fileIndex++}.kt",24  packageFqName: FqName = FqName("com.ivianuu.essentials.integrationtests")25) = SourceFile.kotlin(26  name = name,27  contents = buildString {28    appendLine("package $packageFqName")29    appendLine()...TicketingTest.kt
Source:TicketingTest.kt  
1package ch.frequenzdieb.ticket23import ch.frequenzdieb.common.BaseHelper.Dsl.insert4import ch.frequenzdieb.common.BaseIntegrationTest5import ch.frequenzdieb.event.concert.ConcertHelper6import ch.frequenzdieb.payment.PaymentHelper7import ch.frequenzdieb.security.SecurityHelper8import ch.frequenzdieb.ticket.validation.TicketValidationContextFactory9import io.kotest.assertions.throwables.shouldThrow10import io.kotest.inspectors.forOne11import io.kotest.matchers.shouldBe12import io.kotest.matchers.shouldNotBe13import io.kotest.matchers.string.shouldBeEqualIgnoringCase14import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback15import org.jetbrains.kotlin.script.jsr223.KotlinJsr223JvmLocalScriptEngine16import org.springframework.http.MediaType17import org.springframework.web.server.ResponseStatusException18import javax.script.ScriptEngineManager1920internal class TicketingTest(21    private val ticketService: TicketService,22    private val ticketingHelper: TicketingHelper,23    private val ticketTypeHelper: TicketTypeHelper,24    private val validationContextFactory: TicketValidationContextFactory,25    private val concertHelper: ConcertHelper,26    private val securityHelper: SecurityHelper,27    private val paymentHelper: PaymentHelper28) : BaseIntegrationTest({29    // This is only needed when running in IntelliJ and makes me sick!30    setIdeaIoUseFallback()3132    val restClient = securityHelper.initAccountsForRestClient()3334    describe("using a validation rule on a ticket") {35        it("should throw a validation-error if no more tickets left") {36            val typeName = "testType"3738            val event = concertHelper.createConcert().insert()39            val type = ticketTypeHelper.createTicketType(40                name = typeName,41                validationRules = listOf("3 availableOfType \"$typeName\"")42            ).insert()4344            val fakeTickets = ticketingHelper.createFakeTicket(3) {45                createFakeTicket(46                    event = event,47                    type = type48                )49            }.insert()5051            val fakeTicket = fakeTickets52                .first().copy()53                .apply { id = null }5455            val scriptEngine = ScriptEngineManager().getEngineByExtension("kts") as KotlinJsr223JvmLocalScriptEngine5657            val script =58                """59                3 availableOfType "${type.id}"60                """.trimIndent()6162            shouldThrow<ResponseStatusException> {63                validationContextFactory.with(fakeTicket) {64                    rules {65                        scriptEngine.apply {66                            put("scope", this@with)67                            eval("""68                            with (bindings["scope"] as ch.frequenzdieb.ticketing.validation.TicketValidationDsl.Context) {69                                $script70                            }71                            """.trimIndent()72                            )73                        }74                    }75                }76            }77        }78    }7980    describe("when creating a ticket") {81        it("should create a valid ticket") {82            val fakeTicket = ticketingHelper.createFakeTicket()8384            restClient.getAuthenticatedAsUser()85                .post().uri(ticketRoute)86                .bodyValue(fakeTicket)87                .accept(MediaType.APPLICATION_JSON)88                .exchange()89                .expectStatus().isCreated90                .expectBody(TicketCreateResponse::class.java)91                .returnResult()92                .run {93                    responseBody shouldNotBe null94                    responseBody?.qrCode shouldNotBe null95                    responseBody?.qrCode shouldNotBe ""96                    responseBody?.qrCode!!97                }98                .let { createdTicketQRCode ->99                    restClient.getAuthenticatedAsAdmin()100                        .get().uri { it101                            .path(ticketRoute)102                            .queryParam("subscriptionId", fakeTicket.subscriptionId)103                            .queryParam("eventId", fakeTicket.eventId)104                            .build()105                        }106                        .accept(MediaType.APPLICATION_JSON)107                        .exchange()108                        .expectStatus().isOk109                        .expectBodyList(Ticket::class.java)110                        .returnResult()111                        .apply {112                            responseBody shouldNotBe null113                            responseBody!!.forOne {114                                ticketService.createQRCode(it) shouldBeEqualIgnoringCase createdTicketQRCode115                            }116                        }117                }118        }119120        describe("when invalidating a ticket") {121            it("should set ticket to invalid") {122                val fakeTicket = ticketingHelper.createFakeTicket().insert()123124                paymentHelper.insertTransaction(125                    reference = fakeTicket.id!!,126                    amount = 10,127                    currency = "CHF"128                )129130                restClient.getAuthenticatedAsAdmin()131                    .put().uri("$ticketRoute/invalidate")132                    .bodyValue(TicketInvalidationRequest(133                        qrCodeValue = ticketService.encoder(fakeTicket.id!!.toByteArray()),134                        eventId = fakeTicket.eventId135                    ))136                    .accept(MediaType.APPLICATION_JSON)137                    .exchange()138                    .expectStatus().isOk139                    .expectBody()140                    .jsonPath("$.isValid")141                    .value<Boolean> { it shouldBe false }142            }143        }144    }145})
...build.gradle.kts
Source:build.gradle.kts  
...18}19dependencies {20  compileOnly(project(":prelude"))21  compileOnly(kotlin("stdlib-jdk8"))22  compileOnly("com.intellij:openapi:$OPENAPI_VERSION")23  compileOnly("org.jetbrains.kotlin:kotlin-scripting-compiler-embeddable:1.5.0")24  compileOnly("io.arrow-kt:arrow-meta:$ARROW_META_VERSION")25  compileOnly("org.jetbrains.kotlin:kotlin-script-util:$KOTLIN_VERSION") {26      exclude(group = "org.jetbrains.kotlin", module = "kotlin-stdlib")27      exclude(group = "org.jetbrains.kotlin", module = "kotlin-compiler")28      exclude(group = "org.jetbrains.kotlin", module = "kotlin-compiler-embeddable")29  }30  testImplementation(project(":prelude"))31  testImplementation("io.arrow-kt:arrow-meta:$ARROW_META_VERSION")32  testImplementation("io.arrow-kt:meta-test:$ARROW_META_VERSION")33  testImplementation("io.kotest:kotest-framework-api:4.3.1")34  testImplementation("io.kotest:kotest-property:4.3.1")35  testImplementation("io.kotest:kotest-runner-junit5-jvm:4.3.1")36  // Required for integration test of plugin37  testImplementation("io.ktor:ktor-client-mock:$KTOR_VERSION")38  testImplementation("io.ktor:ktor-client-mock-jvm:$KTOR_VERSION")39  testImplementation("io.arrow-kt:arrow-meta-prelude:$ARROW_META_VERSION")40  testImplementation("io.ktor:ktor-client-core:$KTOR_VERSION")41  testImplementation("io.ktor:ktor-http:$KTOR_VERSION")42  testImplementation("io.ktor:ktor-client-core-jvm:$KTOR_VERSION")43  testImplementation("io.ktor:ktor-client-cio:$KTOR_VERSION")44  testImplementation("io.ktor:ktor-client-json-jvm:$KTOR_VERSION")45  testImplementation("io.ktor:ktor-client-jackson:$KTOR_VERSION")46  testImplementation("io.ktor:ktor-client-logging-jvm:$KTOR_VERSION")47  testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.6")48  testImplementation("org.slf4j:slf4j-simple:1.7.30")49}50tasks.withType<Test> {51  useJUnitPlatform()52}53val createNewPlugin = tasks.create<Jar>("createNewPlugin") {54    archiveBaseName.set("konnekt-plugin")55    dependsOn("classes")56    from("build/classes/kotlin/main")57    from("build/resources/main")58    from(59        zipTree(sourceSets.main.get().compileClasspath.find {60          it.absolutePath.contains(Paths.get("konnekt", "prelude").toString())61        }!!)62    )63    from(64        zipTree(sourceSets.main.get().compileClasspath.find {65            it.absolutePath.contains(Paths.get("arrow-kt", "arrow-meta").toString())66        }!!)67    ) {68        exclude("META-INF/services/org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar")69    }70}71tasks.withType<com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar> {72  configurations = listOf(project.configurations.compileOnly.get())73  relocate("org.jetbrains.kotlin.com.intellij", "com.intellij")74  dependencies {75    exclude(dependency("org.jetbrains.kotlin:kotlin-stdlib"))76    // and its transitive dependencies:77    exclude(dependency("org.jetbrains.kotlin:kotlin-stdlib-common"))78    exclude(dependency("org.jetbrains:annotations"))79    exclude(dependency("com.intellij:openapi"))80    // and its transitive dependencies:81    exclude(dependency("com.intellij:extensions"))82    exclude(dependency("com.intellij:annotations"))83  }84}85val conf = configurations.create("createNewPlugin")86val pluginArtifact = artifacts.add(conf.name, createNewPlugin)87publishing {88  publications {89    val plugin by creating(MavenPublication::class.java) {90      artifactId = "konnekt-plugin"91      artifact(pluginArtifact)92    }93  }94}95tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().all {96  kotlinOptions {...SettingsEditorPanel.kt
Source:SettingsEditorPanel.kt  
1package io.kotest.plugin.intellij2import com.intellij.application.options.ModuleDescriptionsComboBox3import com.intellij.execution.ui.CommonJavaParametersPanel4import com.intellij.execution.ui.ConfigurationModuleSelector5import com.intellij.execution.ui.DefaultJreSelector6import com.intellij.execution.ui.JrePathEditor7import com.intellij.execution.ui.ShortenCommandLineModeCombo8import com.intellij.openapi.options.SettingsEditor9import com.intellij.openapi.project.Project10import com.intellij.openapi.ui.LabeledComponent11import com.intellij.ui.TextFieldWithHistory12import javax.swing.JPanel13class SettingsEditorPanel(project: Project) : SettingsEditor<KotestConfiguration>() {14   private lateinit var panel: JPanel15   private lateinit var commonJavaParameters: CommonJavaParametersPanel16   private lateinit var jrePathEditor: JrePathEditor17   private lateinit var testPath: LabeledComponent<TextFieldWithHistory>18   private lateinit var specName: LabeledComponent<TextFieldWithHistory>19   private lateinit var packageName: LabeledComponent<TextFieldWithHistory>20   private lateinit var module: LabeledComponent<ModuleDescriptionsComboBox>21   private lateinit var myShortenClasspathModeCombo: LabeledComponent<ShortenCommandLineModeCombo>22   private var moduleSelector: ConfigurationModuleSelector23   init {24      moduleSelector = ConfigurationModuleSelector(project, module.component)25      jrePathEditor.setDefaultJreSelector(DefaultJreSelector.fromModuleDependencies(module.component, false))...im.tony.project.kotlin-common-conventions.gradle.kts
Source:im.tony.project.kotlin-common-conventions.gradle.kts  
...14  maven(url = "https://jitpack.io")15  maven(url = "https://oss.sonatype.org/content/repositories/snapshots/")16  maven(url = "https://dl.bintray.com/kotlin/kotlin-plugin/")17  maven(url = "https://kotlin.bintray.com/kotlin-dependencies")18  maven(url = "https://jetbrains.bintray.com/intellij-third-party-dependencies/")19  maven(url = "https://dl.bintray.com/arrow-kt/arrow-kt/")20  maven(url = "https://dl.bintray.com/konform-kt/konform")21  // For ArrowFx snapshot builds22  // maven(url = "https://oss.jfrog.org/artifactory/oss-snapshot-local/")23}24dependencies {25  // Align versions of all Kotlin components26  implementation(platform(Deps.Kotlin.WithBom.Bom))27  // Kotlin StdLibs28  implementation(Deps.Kotlin.WithBom.Stdlib.Jdk8)29  implementation(Deps.Kotlin.WithBom.Stdlib.Common)30  implementation(Deps.Kotlin.WithBom.Stdlib.Core)31  // Align versions of all KotlinX Coroutine Libs32  implementation(platform(Deps.KotlinX.Coroutines.WithBom.Bom))...DisabledTestLineMarker.kt
Source:DisabledTestLineMarker.kt  
1package io.kotest.plugin.intellij.linemarker2import com.intellij.codeInsight.daemon.LineMarkerInfo3import com.intellij.codeInsight.daemon.LineMarkerProvider4import com.intellij.diff.util.DiffUtil5import com.intellij.icons.AllIcons6import com.intellij.psi.PsiElement7import com.intellij.psi.PsiWhiteSpace8import com.intellij.psi.impl.source.tree.LeafPsiElement9import io.kotest.plugin.intellij.MainEditorLineMarkerInfo10import io.kotest.plugin.intellij.psi.enclosingKtClass11import io.kotest.plugin.intellij.psi.specStyle12import org.jetbrains.kotlin.idea.inspections.findExistingEditor13import org.jetbrains.kotlin.psi.KtAnnotationEntry14import org.jetbrains.kotlin.psi.KtDeclarationModifierList15import org.jetbrains.kotlin.psi.KtImportDirective16import org.jetbrains.kotlin.psi.KtImportList17import org.jetbrains.kotlin.psi.KtPackageDirective18/**19 * Adds an icon to the gutter for tests which are disabled.20 */21class DisabledTestLineMarker : LineMarkerProvider {22   // icons list https://jetbrains.design/intellij/resources/icons_list/23   private val icon = AllIcons.RunConfigurations.TestIgnored24   override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {25      // the docs say to only run a line marker for a leaf26      return when (element) {27         // ignoring white space elements will save a lot of lookups28         is PsiWhiteSpace -> null29         is LeafPsiElement -> {30            // we don't show these line markers inside a diff31            val editor = element.findExistingEditor() ?: return null32            if (DiffUtil.isDiffEditor(editor)) return null33            when (element.context) {34               // rule out some common entries that can't possibly be test markers for performance35               is KtAnnotationEntry, is KtDeclarationModifierList, is KtImportDirective, is KtImportList, is KtPackageDirective -> null36               else -> markerForTest(element)...InterpolatedTestLineMarker.kt
Source:InterpolatedTestLineMarker.kt  
1package io.kotest.plugin.intellij.linemarker2import com.intellij.codeInsight.daemon.LineMarkerInfo3import com.intellij.codeInsight.daemon.LineMarkerProvider4import com.intellij.icons.AllIcons5import com.intellij.psi.PsiElement6import com.intellij.psi.PsiWhiteSpace7import com.intellij.psi.impl.source.tree.LeafPsiElement8import io.kotest.plugin.intellij.MainEditorLineMarkerInfo9import io.kotest.plugin.intellij.psi.enclosingKtClass10import io.kotest.plugin.intellij.psi.specStyle11import org.jetbrains.kotlin.asJava.classes.KtLightClass12import org.jetbrains.kotlin.psi.KtAnnotationEntry13import org.jetbrains.kotlin.psi.KtClassOrObject14import org.jetbrains.kotlin.psi.KtDeclarationModifierList15import org.jetbrains.kotlin.psi.KtImportDirective16import org.jetbrains.kotlin.psi.KtImportList17import org.jetbrains.kotlin.psi.KtPackageDirective18/**19 * Adds an icon to the gutter for tests which have an interpolated name.20 */21class InterpolatedTestLineMarker : LineMarkerProvider {22   private val text = "Tests with an interpolated name cannot be run using the plugin."23   // icons list https://jetbrains.design/intellij/resources/icons_list/24   private val icon = AllIcons.RunConfigurations.TestUnknown25   override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {26      // the docs say to only run a line marker for a leaf27      return when (element) {28         // ignoring white space elements will save a lot of lookups29         is PsiWhiteSpace -> null30         is LeafPsiElement -> {31            when (element.context) {32               // rule out some common entries that can't be individual tests for performance33               is KtAnnotationEntry, is KtDeclarationModifierList, is KtClassOrObject, is KtLightClass, is KtImportDirective, is KtImportList, is KtPackageDirective -> null34               else -> markerForTest(element)35            }36         }37         else -> null...kotlin-jvm.gradle.kts
Source:kotlin-jvm.gradle.kts  
1package kotka.convention2import org.jetbrains.kotlin.gradle.tasks.KotlinCompile3plugins {4  id("kotka.convention.subproject")5  kotlin("jvm")6  `java-library`7}8dependencies {9  implementation(platform("org.jetbrains.kotlin:kotlin-bom"))10  val junitVersion = "5.8.2"11  testImplementation(platform("org.junit:junit-bom:$junitVersion"))12  testImplementation("org.junit.jupiter:junit-jupiter")13  testRuntimeOnly("org.junit.platform:junit-platform-launcher") {14    because("Only needed to run tests in a version of IntelliJ IDEA that bundles older versions")15  }16  val kotestVersion = "5.2.3"17  testImplementation(platform("io.kotest:kotest-bom:$kotestVersion"))18  testImplementation("io.kotest:kotest-runner-junit5")19  testImplementation("io.kotest:kotest-assertions-core")20  testImplementation("io.kotest:kotest-property")21  testImplementation("io.kotest:kotest-assertions-json")22  testImplementation("io.mockk:mockk:1.12.3")23}24val projectJvmTarget = "1.8"25val projectJvmVersion = "8"26val projectKotlinTarget = "1.6"27kotlin {28  jvmToolchain {29    (this as JavaToolchainSpec).languageVersion.set(JavaLanguageVersion.of(projectJvmVersion))30  }31}32tasks.withType<KotlinCompile>().configureEach {33  kotlinOptions {34    jvmTarget = projectJvmTarget35    apiVersion = projectKotlinTarget36    languageVersion = projectKotlinTarget37  }38  kotlinOptions.freeCompilerArgs += listOf(39    "-opt-in=kotlin.RequiresOptIn",40    "-opt-in=kotlin.ExperimentalStdlibApi",41    "-opt-in=kotlin.time.ExperimentalTime",42//    "-opt-in=kotlinx.coroutines.ExperimentalCoroutinesApi",43//    "-opt-in=kotlinx.serialization.ExperimentalSerializationApi",44  )45}46tasks.compileTestKotlin {47  kotlinOptions.freeCompilerArgs += "-opt-in=io.kotest.common.ExperimentalKotest"48}49tasks.withType<Test> {50  useJUnitPlatform()51}52java {53  withJavadocJar()54  withSourcesJar()55}...intellij
Using AI Code Generation
1    import io.kotest.core.spec.style.WordSpec2    import io.kotest.matchers.shouldBe3    class WordSpecTest : WordSpec({4        "WordSpec" should {5            "have a test" {6            }7            "throw an exception" {8                shouldThrow<RuntimeException> {9                    throw RuntimeException()10                }11            }12        }13    })14    e: /Users/michael/Developer/AndroidStudioProjects/kotest-test/src/test/kotlin/WordSpecTest.kt: (21, 17): Unresolved reference: shouldThrow15    e: /Users/michael/Developer/AndroidStudioProjects/kotest-test/src/test/kotlin/WordSpecTest.kt: (21, 17): Unresolved reference: shouldThrow16    e: /Users/michael/Developer/AndroidStudioProjects/kotest-test/src/test/kotlin/WordSpecTest.kt: (20, 5): Expecting a top level declarationintellij
Using AI Code Generation
1import io.kotest.core.spec.style.StringSpec2class StringSpecExampleTest : StringSpec() {3init {4"test" {5}6}7}8import io.kotest.core.spec.style.StringSpec9import org.junit.jupiter.api.Test10class StringSpecExampleTest : StringSpec() {11fun test() {12}13}14import io.kotest.core.spec.style.StringSpec15import org.junit.Test16class StringSpecExampleTest : StringSpec() {17fun test() {18}19}20import io.kotest.core.spec.style.StringSpec21import junit.framework.TestCase22class StringSpecExampleTest : StringSpec(), TestCase {23fun test() {24}25}26import io.kotest.core.spec.style.StringSpec27import junit.framework.TestCase28class StringSpecExampleTest : StringSpec(), TestCase {29fun test() {30}31}32import io.kotest.core.spec.style.StringSpec33import junit.framework.TestCase34class StringSpecExampleTest : StringSpec(), TestCase {35fun test() {36}37}38import io.kotest.core.spec.style.StringSpec39import junit.framework.TestCase40class StringSpecExampleTest : StringSpec(), TestCase {41fun test() {42}43}44import io.kotest.core.spec.style.StringSpec45import junit.framework.TestCase46class StringSpecExampleTest : StringSpec(), TestCase {47fun test() {48}49}50import io.kotest.core.spec.style.StringSpec51import junit.framework.TestCase52class StringSpecExampleTest : StringSpec(), TestCase {53fun test() {54}55}56import io.kotest.core.spec.styleintellij
Using AI Code Generation
1import io.kotest.common.ExperimentalKotest  2import io.kotest.core.spec.style.StringSpec  3import io.kotest.matchers.shouldBe4class StringSpecExampleTest : StringSpec() {  5override fun isInstancePerTest(): Boolean = true  6init {  7“a test” {  8}  9}  10}11class StringSpecExampleTest : StringSpec() {  12override fun isInstancePerTest(): Boolean = true  13init {  14“a test” {  15}  16}  17}18class StringSpecExampleTest : StringSpec({  19“a test” {  20}  21})  intellij
Using AI Code Generation
1val stringSpec = io.kotest.core.spec.style.stringSpec {2"this is a test" {3}4}5val stringSpec = io.kotest.core.spec.style.stringSpec {6"this is a test" {7}8}9val stringSpec = io.kotest.core.spec.style.stringSpec {10"this is a test" {11}12}13val stringSpec = io.kotest.core.spec.style.stringSpec.StringSpecDsl {14"this is a test" {15}16}17val stringSpec = io.kotest.core.spec.style.stringSpec.StringSpecDsl.Context {18"this is a test" {19}20}21val stringSpec = io.kotest.core.spec.style.stringSpec.StringSpecDsl.Context.TestDsl {22"this is a test" {23}24}25val stringSpec = io.kotest.core.spec.style.stringSpec.StringSpecDsl.Context.TestDsl.TestContext {26"this is a test" {27}28}29val stringSpec = io.kotest.core.spec.style.stringSpec.StringSpecDsl.Context.TestDsl.TestContext.TestBuilder {30"this is a test" {31}32}33val stringSpec = io.kotest.core.spec.style.stringSpec.StringSpecDsl.Context.TestDsl.TestContext.TestBuilder.TestWithConfigBuilder {34"this is a test" {intellij
Using AI Code Generation
1    val myClass = MyClass()2    myClass.doSomething()3}4compileKotlin {5}6val files = listOf("file1.txt", "file2.txt", "file3.txt")7val newFiles = files.map {  }8class MyClass {9    fun getMyVar(): Int {10    }11}12class MyClassTest : StringSpec({13    "getMyVar should return the value of myVar" {14        val myClass = MyClass()15        myClass.getMyVar() shouldBe 016    }17})18class MyClass {19    fun getMyVar(): Int {20    }21}22class MyClassTest : StringSpec({23    "getMyVar should return the value of myVar" {24        val myClass = MyClass()25        myClass.getMyVar() shouldBe 026    }27})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!!
