Best Kotest code snippet using io.kotest.core.test.config.enabled
PingProducerTest.kt
Source:PingProducerTest.kt
...15import org.springframework.kafka.core.KafkaTemplate16class PingProducerTest : DescribeSpec({17 describe("PingProducer") {18 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)19 it("should send a message when config is enabled") {20 val expectedMessage = "ping"21 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))22 pingProducer.sendMessage(expectedMessage)23 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }24 }25 it("should NOT send a message when config is disabled") {26 val ex = shouldThrow<KafkaIntegrationDisabledException> {27 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = false))28 pingProducer.sendMessage("ping")29 }30 ex.message shouldBe null31 }32 }33})34class PingProducerFreeSpecTest : FreeSpec({35 "PingProducer" - {36 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)37 "when config is enabled" - {38 "should send a message" {39 val expectedMessage = "ping"40 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))41 pingProducer.sendMessage(expectedMessage)42 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }43 }44 }45 }46})47class PingProducerWordSpecTest : WordSpec({48 "PingProducer" When {49 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)50 "config is enabled" Should {51 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))52 "send a message" {53 val expectedMessage = "ping"54 pingProducer.sendMessage(expectedMessage)55 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }56 }57 }58 }59})60class PingProducerBehaviorSpecTest : BehaviorSpec({61 Given("PingProducer") {62 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)63 When("config is enabled") {64 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))65 Then("sends a message") {66 val expectedMessage = "ping"67 pingProducer.sendMessage(expectedMessage)68 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }69 }70 }71 }72})73// ExpectSpec is similar to FunSpec / ShouldSpec74class PingProducerExpectSpecTest : ExpectSpec({75 context("PingProducer") {76 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)77 expect("should send a message when config is enabled") {78 val expectedMessage = "ping"79 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))80 pingProducer.sendMessage(expectedMessage)81 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }82 }83 }84})85class PingProducerFunSpecTest : FunSpec({86 context("PingProducer") {87 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)88 test("should send a message when config is enabled") {89 val expectedMessage = "ping"90 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))91 pingProducer.sendMessage(expectedMessage)92 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }93 }94 }95})96class PingProducerShouldSpecTest : ShouldSpec({97 context("PingProducer") {98 val mockKafkaTemplate = mockk<KafkaTemplate<String, String>>(relaxed = true)99 should("should send a message when config is enabled") {100 val expectedMessage = "ping"101 val pingProducer = PingProducer(mockKafkaTemplate, KafkaIntegrationConfig(enabled = true))102 pingProducer.sendMessage(expectedMessage)103 verify { mockKafkaTemplate.send("ping-topic", expectedMessage) }104 }105 }106})...
gradle-kotlin-setup-plugin.gradle.kts
Source:gradle-kotlin-setup-plugin.gradle.kts
...57 autoCorrect = false58 buildUponDefaultConfig = true59 config = files(configFilePath())60 reports {61 html.enabled = true62 xml.enabled = true63 txt.enabled = true64 }65}66tasks.find { it.name == "generateLombokConfig" }?.enabled = false67tasks68 .getByName("check")69 .dependsOn("detekt")70tasks71 .withType<KotlinCompile>()72 .configureEach {73 with(kotlinOptions) {74 jvmTarget =75 project76 .convention77 .getPlugin<JavaPluginConvention>()78 .sourceCompatibility79 .ordinal80 .let {81 val version = it + 182 if (version <= 8) "1.$version" else "$version"83 }84 freeCompilerArgs =85 listOf(86 "-Xjsr305=strict",87 "-Xjvm-default=all-compatibility"88 )89 kapt.includeCompileClasspath = false90 }91 }92tasks93 .filter { it.name in setOf("compileJava", "compileTestJava") }94 .filter { it.enabled }95 .map { it as JavaCompile }96 .filter { it.source.asFileTree.files.isNotEmpty() }97 .forEach { task ->98 task.source =99 project100 .properties["delombok"]101 .let { it as Delombok }102 .target103 .asFileTree104 }105fun DetektExtension.configFilePath() =106 javaClass107 .getResourceAsStream("/config/detekt.yml")!!108 .bufferedReader(Charsets.UTF_8)...
build.gradle.kts
Source:build.gradle.kts
1plugins {2 `java-gradle-plugin`3 jacoco4 kotlin("jvm") version "1.3.72"5 id("org.danilopianini.git-sensitive-semantic-versioning") version "0.2.2"6 id("com.gradle.plugin-publish") version "0.12.0"7 id("pl.droidsonroids.jacoco.testkit") version "1.0.7"8 id("org.jlleitschuh.gradle.ktlint") version "9.4.1"9 id("io.gitlab.arturbosch.detekt") version "1.14.1"10}11group = "it.unibo.lss2020"12gitSemVer {13 version = computeGitSemVer()14}15repositories {16 jcenter()17}18dependencies {19 implementation(gradleApi()) // Implementation: available at compile and runtime, non transitive20 testImplementation(gradleTestKit()) // Test implementation: available for testing compile and runtime21 testImplementation("io.kotest:kotest-runner-junit5:4.1.3") // for kotest framework22 testImplementation("io.kotest:kotest-assertions-core:4.1.3") // for kotest core assertions23 testImplementation("io.kotest:kotest-assertions-core-jvm:4.1.3") // for kotest core jvm assertions24 detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.14.1")25}26tasks.withType<Test> {27 useJUnitPlatform() // Use JUnit 5 engine28 testLogging.showStandardStreams = true29 testLogging {30 showCauses = true31 showStackTraces = true32 showStandardStreams = true33 events(*org.gradle.api.tasks.testing.logging.TestLogEvent.values())34 exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL35 }36}37// This task creates a file with a classpath descriptor, to be used in tests38val createClasspathManifest by tasks.registering {39 val outputDir = file("$buildDir/$name")40 inputs.files(sourceSets.main.get().runtimeClasspath)41 outputs.dir(outputDir)42 doLast {43 outputDir.mkdirs()44 file("$outputDir/plugin-classpath.txt").writeText(sourceSets.main.get().runtimeClasspath.joinToString("\n"))45 }46}47// Add the classpath file to the test runtime classpath48dependencies {49 // This way "createClasspathManifest" is always executed before the tests!50 // Gradle auto-resolves dependencies if there are dependencies on inputs/outputs51 testRuntimeOnly(files(createClasspathManifest))52}53pluginBundle { // These settings are set for the whole plugin bundle54 website = "https://danysk.github.io/Course-Laboratory-of-Software-Systems/"55 vcsUrl = "https://github.com/DanySK/Course-Laboratory-of-Software-Systems"56 tags = listOf("example", "greetings", "lss", "unibo")57}58gradlePlugin {59 plugins {60 create("GradleLatex") { // One entry per plugin61 id = "${project.group}.${project.name}"62 displayName = "LSS Greeting plugin"63 description = "Example plugin for the LSS course"64 implementationClass = "it.unibo.lss.firstplugin.GreetingPlugin"65 }66 }67}68tasks.jacocoTestReport {69 reports {70 // xml.isEnabled = true71 html.isEnabled = true72 }73}74tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {75 kotlinOptions {76 allWarningsAsErrors = true77 }78}79detekt {80 failFast = true // fail build on any finding81 buildUponDefaultConfig = true // preconfigure defaults82 config = files("$projectDir/config/detekt.yml")83}...
CategoryRepositoryUpdateSpec.kt
Source:CategoryRepositoryUpdateSpec.kt
...17@Transactional(propagation = Propagation.NOT_SUPPORTED)18@DataJpaTest(19 showSql = true,20 properties = [21 "spring.flyway.enabled=false",22 "spring.jpa.hibernate.ddl-auto=create"23 ]24)25class CategoryRepositoryUpdateSpec(26 private val categoryRepository: CategoryRepository27) : StringSpec() {28 init {29 "ID를 íµí Category ìì ì±ê³µ Test" {30 val targetName = "changed"31 val categoryChildren = Mock.category().chunked(10, 10).single()32 val targetCategory = Mock.category(children = categoryChildren).single()33 val savedCategory = categoryRepository.save(targetCategory)34 savedCategory.name = targetName35 val updatedCategory = categoryRepository.save(savedCategory)...
CategoryRepositorySelectSpec.kt
Source:CategoryRepositorySelectSpec.kt
...14@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" {27 val targetCategory = Mock.category().single()28 val savedCategory = categoryRepository.save(targetCategory)29 val savedCategoryId = savedCategory.id ?: throw IllegalArgumentException()30 val foundCategories = categoryRepository.findAll()31 foundCategories shouldHaveSize 132 foundCategories shouldHave singleElement { it.id == savedCategoryId }...
AssertSoftlyWithInContextTest.kt
Source:AssertSoftlyWithInContextTest.kt
...5import io.kotest.core.test.TestCaseConfig6import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder7class AssertSoftlyWithInContextTest : FunSpec(){8 init {9 defaultTestConfig = TestCaseConfig(enabled = true)10 val users = listOf("user1", "user2")11 val samplePermissions = mapOf("table" to listOf("SELECT", "UPDATE"))12 context("validate user permissions") {13 users.forEach { user ->14 test("$user should have specific permissions") {15 assertSoftly {16 samplePermissions.entries.forEach { (tableName, permissions) ->17 withClue("$user should only have select access to $tableName") {18 permissions shouldContainExactlyInAnyOrder listOf("SELECT")19 }20 }21 }22 }23 }...
EnabledFlags.kt
Source:EnabledFlags.kt
...10val disableDanger: (TestCase) -> Enabled = {11 if (it.name.testName.startsWith("danger"))12 Enabled.disabled("we don't like danger!")13 else14 Enabled.enabled15}16class EnabledFlags : StringSpec({17 "length should return size of string".config(18 enabled = false19 ) {20 "hello world".length shouldBe 1021 }22 "startsWith should test for a prefix".config(23 enabledIf = disableStartsWith24 ) {25 "sandbox" should startWith("hello")26 }27 "danger test".config(28 enabledOrReasonIf = disableDanger29 ) {30 "sandbox" should startWith("hello")31 }32})...
CIOnlySpec.kt
Source:CIOnlySpec.kt
...8/** [io.kotest.core.annotation.EnabledIf] annotation with [io.kotest.core.annotation.EnabledCondition] */9@EnabledIf(OnCICondition::class)10class CIOnlySpec : FreeSpec() {11 init {12 "Test for Jenkins".config(enabledIf = jenkinsTestCase, enabled = System.getProperty("CI") == "true") { }13 }14}15/** typealias EnabledIf = (TestCase) -> Boolean */16val jenkinsTestCase: io.kotest.core.test.EnabledIf = { testCase: TestCase -> testCase.displayName.contains("Jenkins") }17/** Separate class implementation [io.kotest.core.annotation.EnabledCondition] */18class OnCICondition: EnabledCondition {19 override fun enabled(specKlass: KClass<out Spec>) = System.getProperty("CI") == "true"20}...
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!!