Best Kotest code snippet using io.kotest.property.lifecycle.lifecycle
settings.gradle.kts
Source:settings.gradle.kts
...88 .versionRef("bindingLibVersion")89 alias("bindingRecyclerView").to("me.tatarka.bindingcollectionadapter2", "bindingcollectionadapter-recyclerview")90 .versionRef("bindingLibVersion")91 bundle("bindingLib", listOf("bindingBase", "bindingRecyclerView"))92 version("lifecycle", "2.4.0-alpha03")93 alias("viewmodel-ktx").to("androidx.lifecycle", "lifecycle-viewmodel-ktx").versionRef("lifecycle")94 alias("livedata-ktx").to("androidx.lifecycle", "lifecycle-livedata-ktx").versionRef("lifecycle")95 alias("lifecycle-common").to("androidx.lifecycle", "lifecycle-common-java8").versionRef("lifecycle")96 alias("lifecycle-ktx").to("androidx.lifecycle", "lifecycle-runtime-ktx").versionRef("lifecycle")97 bundle("lifecycle", listOf("viewmodel-ktx", "livedata-ktx", "lifecycle-common", "lifecycle-ktx"))98 val navigationVersion: String by settings99 version("navigation", navigationVersion)100 alias("navigation-fragment").to("androidx.navigation", "navigation-fragment-ktx").versionRef("navigation")101 alias("navigation-dynamic")102 .to("androidx.navigation", "navigation-dynamic-features-fragment")103 .versionRef("navigation")104 alias("navigation-ui-ktx").to("androidx.navigation", "navigation-ui-ktx").versionRef("navigation")105 bundle("navigation", listOf("navigation-fragment", "navigation-dynamic", "navigation-ui-ktx"))106 version("room", "2.+")107 alias("room-ktx").to("androidx.room", "room-ktx").versionRef("room")108 alias("room-runtime").to("androidx.room", "room-runtime").versionRef("room")109 bundle("room", listOf("room-ktx", "room-runtime"))110 alias("room.compiler").to("androidx.room", "room-compiler").versionRef("room")111 val hiltVersion: String by settings...
KotestAllureExecution.kt
Source:KotestAllureExecution.kt
1package ru.iopump.kotest.allure.api2import io.kotest.core.spec.Spec3import io.kotest.core.test.Description4import io.kotest.core.test.TestCase5import io.qameta.allure.Allure6import io.qameta.allure.AllureLifecycle7import io.qameta.allure.model.FixtureResult8import io.qameta.allure.model.Status9import ru.iopump.kotest.allure.KotestAllureListener10import ru.iopump.kotest.allure.api.KotestAllureConstant.VAR11import ru.iopump.kotest.allure.api.KotestAllureExecution.PROJECT_UUID12import ru.iopump.kotest.allure.api.KotestAllureExecution.containerUuid13import ru.iopump.kotest.allure.api.KotestAllureExecution.setUpFixture14import ru.iopump.kotest.allure.helper.InternalUtil.logger15import ru.iopump.kotest.allure.helper.InternalUtil.prop16import ru.iopump.kotest.allure.helper.InternalUtil.safeFileName17import java.io.File18import java.util.UUID19import kotlin.reflect.KClass20/**21 * User API to get access to allure listener execution.22 * For example: create fixture [setUpFixture] or obtain actual [Spec] uuid in Allure Storage - [containerUuid]23 * or project execution root uuid - [PROJECT_UUID]24 */25object KotestAllureExecution {26 private val log = logger<KotestAllureExecution>()27 /**28 * Get current [AllureLifecycle] or extended version for example [Slf4JAllureLifecycle]29 */30 val ALLURE: AllureLifecycle = initAllureLifecycle()31 /**32 * Get container uuid of entire Execution.33 *34 * See [setUpFixture]35 * See [tearDownFixture]36 * See [EXECUTION_START_CALLBACK]37 */38 val PROJECT_UUID = KotestAllureListener.hashCode().toString()39 /**40 * Use to add project level Fixture.41 * Not thread safe. Not final variable.42 *43 * See [setUpFixture]44 * See [tearDownFixture]45 */46 var EXECUTION_START_CALLBACK: (projectUuid: String) -> Unit = { }47 /**48 * Get container uuid of [Spec]49 *50 * See [setUpFixture]51 * See [tearDownFixture]52 */53 val Spec.containerUuid get() = this::class.containerUuid54 /**55 * Get container uuid of [Spec] class56 *57 * See [setUpFixture]58 * See [tearDownFixture]59 */60 val KClass<out Spec>.containerUuid get() = qualifiedName.safeFileName61 /**62 * The longest name for [TestCase.description]63 */64 fun Description.bestName() = names().joinToString("_") { it.displayName }65 /**66 * Create Set Up Fixture for [Spec]67 */68 fun Spec.setUpFixture(69 name: String,70 atomic: Boolean = true,71 fixtureResult: FixtureResult.() -> Unit = {}72 ) = this::class.setUpFixture(name, atomic, fixtureResult)73 /**74 * Create Set Up Fixture for [Spec]75 */76 fun KClass<out Spec>.setUpFixture(77 name: String,78 atomic: Boolean = true,79 fixtureResult: FixtureResult.() -> Unit = {}80 ): String = containerUuid.setUpFixture(name, atomic, fixtureResult)81 /**82 * Create Set Up Fixture by container uuid.83 *84 * See [PROJECT_UUID]85 * See [EXECUTION_START_CALLBACK]86 * See [containerUuid]87 */88 fun String.setUpFixture(89 name: String,90 atomic: Boolean = true,91 fixtureResult: FixtureResult.() -> Unit = {}92 ): String {93 val fixture = FixtureResult()94 .also { it.name = name; it.status = Status.PASSED }95 .also(fixtureResult)96 val uuid = UUID.randomUUID().toString()97 ALLURE.startPrepareFixture(this, uuid, fixture)98 if (atomic) ALLURE.stopFixture(uuid)99 return uuid100 }101 /**102 * Create Tear Down Fixture for [Spec]103 */104 fun Spec.tearDownFixture(105 name: String,106 atomic: Boolean = true,107 fixtureResult: FixtureResult.() -> Unit = {}108 ) = this::class.tearDownFixture(name, atomic, fixtureResult)109 /**110 * Create Tear Down Fixture for [Spec]111 */112 fun KClass<out Spec>.tearDownFixture(113 name: String,114 atomic: Boolean = true,115 fixtureResult: FixtureResult.() -> Unit = {}116 ): String = containerUuid.tearDownFixture(name, atomic, fixtureResult)117 /**118 * Create Tear Down Fixture by container uuid.119 *120 * See [PROJECT_UUID]121 * See [EXECUTION_START_CALLBACK]122 * See [containerUuid]123 */124 fun String.tearDownFixture(125 name: String,126 atomic: Boolean = true,127 fixtureResult: FixtureResult.() -> Unit = {}128 ): String {129 val fixture = FixtureResult()130 .also { it.name = name; it.status = Status.PASSED }131 .also(fixtureResult)132 val uuid = UUID.randomUUID().toString()133 ALLURE.startTearDownFixture(this, uuid, fixture)134 if (atomic) ALLURE.stopFixture(uuid)135 return uuid136 }137 /////////////////138 //// PRIVATE ////139 /////////////////140 private fun initAllureLifecycle(): AllureLifecycle {141 val resultDir = VAR.ALLURE_RESULTS_DIR.prop("build/allure-results")142 val slf4jEnabled = VAR.ALLURE_SLF4J_LOG.prop(true)143 val allureClassRef: String = VAR.ALLURE_LIFECYCLE_CLASS.prop("")144 System.setProperty(VAR.ALLURE_RESULTS_DIR, resultDir)145 clearPreviousResults(File(resultDir))146 return (if (allureClassRef.isNotBlank())147 runCatching { Class.forName(allureClassRef).getConstructor().newInstance() as AllureLifecycle }148 .onFailure { throw RuntimeException("Cannot create AllureLifecycle from class '$allureClassRef'", it) }149 .getOrThrow()150 else (if (slf4jEnabled) Slf4JAllureLifecycle(log) else AllureLifecycle())).also { Allure.setLifecycle(it) }151 }152 private fun clearPreviousResults(dir: File) {153 if (VAR.CLEAR_ALLURE_RESULTS_DIR.prop(true)) {154 if (dir.exists() && dir.isDirectory) {155 runCatching { dir.deleteRecursively() }.getOrElse { log.error("Cannot delete '$dir'", it) }156 }157 }158 }159}...
build.gradle.kts
Source:build.gradle.kts
...66 includeEngines("junit-jupiter", "spek2", "kotest")67 }68 systemProperty("root.project.dir", project.rootProject.rootDir.absolutePath)69 testLogging {70 lifecycle {71 events = mutableSetOf(72 org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED,73 org.gradle.api.tasks.testing.logging.TestLogEvent.PASSED,74 org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED75 )76 exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL77 showExceptions = true78 showCauses = true79 showStackTraces = true80 showStandardStreams = true81 }82 info.events = lifecycle.events83 info.exceptionFormat = lifecycle.exceptionFormat84 }85 val failedTests = mutableListOf<TestDescriptor>()86 val skippedTests = mutableListOf<TestDescriptor>()87 // See https://github.com/gradle/kotlin-dsl/issues/83688 addTestListener(object : TestListener {89 override fun beforeSuite(suite: TestDescriptor) {}90 override fun beforeTest(testDescriptor: TestDescriptor) {}91 override fun afterTest(testDescriptor: TestDescriptor, result: TestResult) {92 when (result.resultType) {93 TestResult.ResultType.FAILURE -> failedTests.add(testDescriptor)94 TestResult.ResultType.SKIPPED -> skippedTests.add(testDescriptor)95 else -> Unit96 }97 }98 override fun afterSuite(suite: TestDescriptor, result: TestResult) {99 if (suite.parent == null) { // root suite100 logger.lifecycle("----")101 logger.lifecycle("Test result: ${result.resultType}")102 logger.lifecycle(103 "Test summary: ${result.testCount} tests, " +104 "${result.successfulTestCount} succeeded, " +105 "${result.failedTestCount} failed, " +106 "${result.skippedTestCount} skipped"107 )108 failedTests109 .takeIf { it.isNotEmpty() }110 ?.prefixedSummary("\tFailed Tests")111 skippedTests112 .takeIf { it.isNotEmpty() }113 ?.prefixedSummary("\tSkipped Tests:")114 }115 }116 private infix fun List<TestDescriptor>.prefixedSummary(subject: String) {117 logger.lifecycle(subject)118 forEach { test -> logger.lifecycle("\t\t${test.displayName()}") }119 }120 private fun TestDescriptor.displayName() =121 parent?.let { "${it.name} - $name" } ?: "$name"122 })123 }124}...
Dependencies.kt
Source:Dependencies.kt
...12 const val appCompat = "1.1.0"13 const val constraintLayout = "1.1.3"14 const val recyclerView = "1.1.0"15 const val coreKtx = "1.2.0"16 const val lifecycleViewModel = "2.2.0"17 const val lifecycleRuntime = "2.2.0"18 const val koin = "2.1.6"19 const val leakCanary = "2.4"20 const val timber = "4.7.1"21 const val retrofit = "2.9.0"22 const val moshi = "1.9.3"23 const val navigationComponent = "2.3.0"24 const val coroutines = "1.3.8"25 const val picasso = "2.5.2"26 const val joda = "2.10.6"27 object Test {28 const val androidxTestExt = "1.1.1"29 const val androidxTest = "1.2.0"30 const val junit = "5.6.2"31 const val espressoCore = "3.2.0"32 const val archUnit = "0.14.1"33 const val coroutines = "1.3.8"34 const val kotest = "4.1.3"35 const val mockk = "1.10.0"36 }37}38object BuildPlugins {39 const val androidGradlePlugin = "4.0.1"40 const val kotlin = "1.3.72"41 const val ktlint = "9.3.0"42 const val owasp = "5.3.2.1"43}44object SupportLibs {45 const val appCompat = "androidx.appcompat:appcompat:${Versions.appCompat}"46 const val constraintLayout = "com.android.support.constraint:constraint-layout:${Versions.constraintLayout}"47 const val androidCoreKtx = "androidx.core:core-ktx:${Versions.coreKtx}"48 const val lifecycleViewModel = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Versions.lifecycleViewModel}"49 const val lifecycleRuntime = "androidx.lifecycle:lifecycle-runtime-ktx:${Versions.lifecycleRuntime}"50 const val recyclerView = "androidx.recyclerview:recyclerview:${Versions.recyclerView}"51}52object Kotlin {53 const val coroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.coroutines}"54}55object Ui {56 const val picasso = "com.squareup.picasso:picasso:${Versions.picasso}"57}58object Navigation {59 const val navigationFragment = "androidx.navigation:navigation-fragment-ktx:${Versions.navigationComponent}"60 const val navigationUi = "androidx.navigation:navigation-ui-ktx:${Versions.navigationComponent}"61}62object Di {63 const val koinAndroid = "org.koin:koin-android:${Versions.koin}"...
Libs.kt
Source:Libs.kt
...29 }30 object Lifecycle {31 private const val version = "2.4.1"32 const val vmKtx =33 "androidx.lifecycle:lifecycle-viewmodel-ktx:$version"34 const val liveData =35 "androidx.lifecycle:lifecycle-livedata-ktx:$version"36 const val runtime =37 "androidx.lifecycle:lifecycle-runtime-ktx:$version"38 const val vmSavedState =39 "androidx.lifecycle:lifecycle-viewmodel-savedstate:$version"40 const val common =41 "androidx.lifecycle:lifecycle-common-java8:$version"42 // Test helpers for LiveData43 const val testLiveData = "androidx.arch.core:core-testing:$version"44 }45 object Navigation {46 const val version = "2.4.1"47 private const val gr = "androidx.navigation"48 const val fragment = "$gr:navigation-fragment-ktx:$version"49 const val ui = "$gr:navigation-ui-ktx:$version"50 const val feature =51 "$gr:navigation-dynamic-features-fragment:$version"52 }53 object RecyclerView {54 private const val version = "1.2.1"55 const val recycler = "androidx.recyclerview:recyclerview:$version"...
Deps.kt
Source:Deps.kt
...39 const val appcompat = "$gr.appcompat:appcompat:1.4.0-beta01"40 const val splash = "$gr.core:core-splashscreen:1.0.0-beta01"41 }42 object Lifecycle {43 private const val group = "androidx.lifecycle"44 private const val version = "2.4.0-rc01"45 // ViewModel46 const val viewModel = "$group:lifecycle-viewmodel-ktx:$version"47 // ViewModel utilities for Compose48 const val VmCompose = "$group:lifecycle-viewmodel-compose:$version"49 }50 object Accompanist {51 private const val version = "0.23.1"52 private const val group = "com.google.accompanist"53 const val systemuicontroller =54 "$group:accompanist-systemuicontroller:$version"55 }56 object Coroutines {57 private const val group = "org.jetbrains.kotlinx"58 private const val version = "1.6.0"59 const val core = "$group:kotlinx-coroutines-core:$version"60 const val android = "$group:kotlinx-coroutines-android:$version"61 const val coroutinesTest = "$group:kotlinx-coroutines-test:$version"62 }...
KiteDslUiTest.kt
Source:KiteDslUiTest.kt
2import android.app.Activity3import android.content.Context4import androidx.fragment.app.Fragment5import androidx.fragment.app.testing.launchFragmentInContainer6import androidx.lifecycle.Lifecycle.State7import androidx.lifecycle.LifecycleOwner8import androidx.lifecycle.SavedStateHandle9import androidx.test.core.app.launchActivity10import io.kotest.assertions.throwables.shouldNotThrowAny11import io.kotest.assertions.throwables.shouldThrow12import io.kotest.core.spec.style.StringSpec13import io.kotest.experimental.robolectric.RobolectricTest14import io.kotest.matchers.shouldBe15import io.kotest.matchers.types.shouldBeSameInstanceAs16import io.kotest.property.checkAll17import io.kotest.property.exhaustive.exhaustive18import jp.co.cyberagent.kite.androidtestcommon.TestActivity19import jp.co.cyberagent.kite.androidtestcommon.TestFragment20import jp.co.cyberagent.kite.androidtestcommon.TestLifecycleOwner21import jp.co.cyberagent.kite.core.requireByType22@RobolectricTest23class KiteDslUiTest : StringSpec({24 "Initialize kiteDsl at INITIALIZED should success" {25 val owner = TestLifecycleOwner()26 owner.lifecycle.currentState = State.INITIALIZED27 shouldNotThrowAny {28 kiteDsl(owner, TestKiteViewModelProvider()) { /* no op */ }29 }30 }31 "Initialize kiteDsl not at INITIALIZED should throw exception" {32 val owner = TestLifecycleOwner()33 val states = listOf(34 State.CREATED, State.STARTED, State.RESUMED, State.DESTROYED35 ).exhaustive()36 checkAll(states) { s ->37 owner.lifecycle.currentState = s38 shouldThrow<IllegalStateException> {39 kiteDsl(owner, TestKiteViewModelProvider()) { /* no op */ }40 }41 }42 }43 "Activity kiteDsl should initialize with correct KiteContext" {44 var invoked = false45 TestActivity.onCreateAction = { activity ->46 activity.kiteDsl {47 kiteContext.requireByType<Activity>() shouldBeSameInstanceAs activity48 kiteContext.requireByType<Context>() shouldBeSameInstanceAs activity49 kiteContext.requireByType<LifecycleOwner>() shouldBeSameInstanceAs activity50 kiteContext.requireByType<SavedStateHandle>()51 invoked = true...
KotestAllureConstant.kt
Source:KotestAllureConstant.kt
...22 /**23 * Set [AllureLifecycle] full class name.24 * Default = [ru.iopump.kotest.allure.api.Slf4JAllureLifecycle].25 */26 const val ALLURE_LIFECYCLE_CLASS = "allure.lifecycle.class"27 /**28 * Set jira ticket pattern in Kotest Test name.29 * Default = '\[([a-zA-Z]+-\d+)]' like [KT-100]30 */31 const val ALLURE_JIRA_PATTERN = "allure.jira.pattern"32 /**33 * Result directory.34 * Default = 'build/allure-results'35 */36 const val ALLURE_RESULTS_DIR = "allure.results.directory"37 /**38 * Clear [ALLURE_RESULTS_DIR] before execution.39 * Default = true - clear40 */...
lifecycle
Using AI Code Generation
1class MyTest : WordSpec() {2override fun beforeTest(testCase: TestCase) {3}4override fun afterTest(testCase: TestCase, result: TestResult) {5}6override fun afterProject() {7}8override fun beforeProject() {9}10}
lifecycle
Using AI Code Generation
1+import io.kotest.property.lifecycle.*2 import io.kotest.property.*3@@ -48,7 +49,7 @@ import io.kotest.property.*4 import io.kotest.property.*5-import io.kotest.property.arbitrary.*6+import io.kotest.property.arbitrary.arbitrary7 import io.kotest.property.*8@@ -56,7 +57,7 @@ import io.kotest.property.*9 import io.kotest.property.*10-import io.kotest.property.arbitrary.*11+import io.kotest.property.arbitrary.arbitrary12 import io.kotest.property.*13@@ -64,7 +65,7 @@ import io.kotest.property.*14 import io.kotest.property.*15-import io.kotest.property.arbitrary.*16+import io.kotest.property.arbitrary.arbitrary17 import io.kotest.property.*18@@ -72,7 +73,7 @@ import io.kotest.property.*19 import io.kotest.property.*20-import io.kotest.property.arbitrary.*21+import io.kotest.property.arbitrary.arbitrary22 import io.kotest.property.*23@@ -80,7 +81,7 @@ import io.kotest.property.*24 import io.kotest.property.*25-import io.kotest.property.arbitrary.*26+import io.kotest.property.arbitrary.arbitrary27 import io.kotest.property.*28@@ -88,7 +89,7 @@ import io.kotest.property.*29 import io.kotest.property.*30-import io.kotest.property.arbitrary.*31+import io.kotest.property.arbitrary.arbitrary
lifecycle
Using AI Code Generation
1+import io.kotest.property.lifecycle.*2 import io.kotest.property.Arb3 import io.kotest.property.Exhaustive4 import io.kotest.property.PropertyTesting5@@ -190,6 +191,7 @@ class PropertyTest : FunSpec() {6 "should be able to use io.kotest.property.lifecycle package" {7 val prop = property {8+ val lifecycle = Lifecycle()9 val a = Arb.int(1..10)10 val b = Arb.int(1..10)11 val c = Arb.int(1..10)12@@ -198,7 +200,7 @@ class PropertyTest : FunSpec() {13 a.generate().value shouldBeLessThan 1114 b.generate().value shouldBeLessThan 1115 c.generate().value shouldBeLessThan 1116- Lifecycle().increment()17+ lifecycle.increment()18 }19 prop.check()20+import io.kotest.core.spec.style.FunSpec21 import io.kotest.matchers.shouldBe22 import org.apache.taverna.lang.beanutils.BeanUtils23@@ -25,7 +26,7 @@ import org.apache.taverna.lang.beanutils.PropertyException24 import org.apache.taverna.lang.beanutils.PropertyNotFoundException25 import org.apache.taverna.lang.beanutils.PropertyUtils26-class BeanUtilsTest extends Specification {27+class BeanUtilsTest : FunSpec() {28 def "test setProperty"() {
lifecycle
Using AI Code Generation
1class MySpec : BehaviorSpec() {2 init {3 Given("a property test") {4 val gen = Gen.int()5 val prop = forAll(gen) { n ->6 }7 Then("the property should hold") {8 prop.check()9 }10 }11 }12}13class MySpec : BehaviorSpec() {14 init {15 Given("a property test") {16 val gen = Gen.int()17 val prop = forAll(gen) { n ->18 }19 Then("the property should hold") {20 prop.check()21 }22 }23 }24}25class MySpec : BehaviorSpec() {26 init {27 Given("a property test") {28 val gen = Gen.int()29 val prop = forAll(gen) { n ->30 }31 Then("the property should hold") {32 prop.check()33 }34 }35 }36}37class MySpec : BehaviorSpec() {38 init {39 Given("a property test") {40 val gen = Gen.int()41 val prop = forAll(gen) { n ->42 }43 Then("the property should hold") {44 prop.check()45 }46 }47 }48}49class MySpec : BehaviorSpec() {50 init {51 Given("a property test") {52 val gen = Gen.int()53 val prop = forAll(gen) { n ->54 }55 Then("the property should hold") {56 prop.check()57 }58 }59 }60}61class MySpec : BehaviorSpec() {62 init {63 Given("a property test") {64 val gen = Gen.int()
lifecycle
Using AI Code Generation
1 property("some property") {2 }3 }4}5class MySpec : StringSpec() {6 override fun beforeTest(testCase: TestCase) {7 db = Database.connect(...)8 }9 override fun afterTest(testCase: TestCase, result: TestResult) {10 db?.close()11 }12 init {13 "test case 1" {14 }15 "test case 2" {16 }17 }18}19class MySpec : StringSpec() {20 override fun beforeSpec(spec: Spec) {21 db = Database.connect(...)22 }23 override fun afterSpec(spec: Spec) {24 db?.close()25 }26 init {27 "test case 1" {28 }29 "test case 2" {30 }31 }32}33class MySpec : StringSpec() {34 override fun beforeContainer(container: Test
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!!