Best Kotest code snippet using io.kotest.common.results
PrimaryDataSourceTest.kt
Source:PrimaryDataSourceTest.kt
...90 val value = Mocks.accountsFromValidator(paginationTwenty)91 coEvery { getDataSource.accountsFromValidator(paginationTwenty) } returns Outcome.Success(value)92 val response = primaryDataSource.fetchAccountsFromValidator(paginationTwenty)93 check(response is Outcome.Success)94 response.value.results.shouldNotBeEmpty()95 response.value.count shouldBeGreaterThan 2096 response.value.results.size shouldBeLessThanOrEqual 2097 }98 @Test99 fun `should fetch list of 20 validators successfully`() = runBlockingTest {100 val value = Mocks.validators(paginationTwenty)101 coEvery { getDataSource.validators(paginationTwenty) } returns Outcome.Success(value)102 val response = primaryDataSource.fetchValidators(paginationTwenty)103 check(response is Outcome.Success)104 response.value.results.shouldNotBeEmpty()105 response.value.count shouldBeGreaterThan 20106 response.value.results.size shouldBeLessThanOrEqual 20107 }108 @Test109 fun `should fetch list of 30 accounts successfully from primary validator`() = runBlockingTest {110 val value = Mocks.accountsFromValidator(paginationThirty)111 coEvery { getDataSource.accountsFromValidator(paginationThirty) } returns Outcome.Success(value)112 val response = primaryDataSource.fetchAccountsFromValidator(paginationThirty)113 check(response is Outcome.Success)114 response.value.results.shouldNotBeEmpty()115 response.value.count shouldBeGreaterThan 0116 response.value.results.size shouldBeLessThanOrEqual 30117 }118 @Test119 fun `should fetch list of 30 validators successfully`() = runBlockingTest {120 val value = Mocks.validators(paginationThirty)121 coEvery { getDataSource.validators(paginationThirty) } returns Outcome.Success(value)122 val response = primaryDataSource.fetchValidators(paginationThirty)123 check(response is Outcome.Success)124 response.value.results.shouldNotBeEmpty()125 response.value.count shouldBeGreaterThan 0126 response.value.results.size shouldBeLessThanOrEqual 30127 }128 @Test129 fun `should fetch account balance successfully from primary validator`() = runBlockingTest {130 val accountNumber = Some.accountNumber131 val value = Mocks.accountBalance()132 coEvery { getDataSource.accountBalance(accountNumber) } returns Outcome.Success(value)133 val response = primaryDataSource.fetchAccountBalance(accountNumber)134 check(response is Outcome.Success)135 response.value.balance shouldBe Some.balance136 }137 @Test138 fun `should fetch account balance lock successfully from primary validator`() = runBlockingTest {139 val accountNumber = Some.accountNumber140 val value = Mocks.accountBalanceLock()...
MultiSourceResultTest.kt
Source:MultiSourceResultTest.kt
...17 val source1 = MultiSourceResultObjectMother.giveMeNumberOfSuccessfulBeskjedEventsForSource(1, expectedSource1, baseEventId = "beskjed")18 val source2 = MultiSourceResultObjectMother.giveMeNumberOfSuccessfulBeskjedEventsForSource(2, expectedSource2, baseEventId = "varsel")19 val sum = source1 + source220 sum.shouldNotBeNull()21 sum.results().size shouldBe (source1.results().size + source2.results().size)22 sum.results() shouldContainAll source1.results()23 sum.results() shouldContainAll source2.results()24 sum.failedSources().size shouldBe (source1.failedSources().size + source2.failedSources().size)25 sum.successFullSources().size shouldBe 226 sum.successFullSources() shouldBe listOf(expectedSource1, expectedSource2)27 sum.hasErrors() shouldBe false28 sum.determineHttpCode() shouldBe HttpStatusCode.OK29 }30 @Test31 fun `Skal summere et vellykket og et feilende resultat til et nytt resultatobjekt`() {32 val expectedSource1 = KildeType.EVENTHANDLER33 val expectedSource2 = KildeType.DIGISOS34 val source1 = MultiSourceResultObjectMother.giveMeNumberOfSuccessfulBeskjedEventsForSource(1, expectedSource1)35 val source2 = MultiSourceResult.createErrorResult<BeskjedDTO, KildeType>(expectedSource2)36 val sum = source1 + source237 sum.shouldNotBeNull()38 sum.results().size shouldBe (source1.results().size + source2.results().size)39 sum.results() shouldContainAll source1.results()40 sum.results() shouldContainAll source2.results()41 sum.failedSources().size shouldBe (source1.failedSources().size + source2.failedSources().size)42 sum.successFullSources().size shouldBe 143 sum.successFullSources() shouldContain expectedSource144 sum.hasErrors() shouldBe true45 sum.determineHttpCode() shouldBe HttpStatusCode.PartialContent46 }47 @Test48 fun `Skal summere to feilede resultater til et nytt resultatobjekt`() {49 val expectedSource1 = KildeType.EVENTHANDLER50 val expectedSource2 = KildeType.DIGISOS51 val source1 = MultiSourceResult.createErrorResult<BeskjedDTO, KildeType>(expectedSource1)52 val source2 = MultiSourceResult.createErrorResult<BeskjedDTO, KildeType>(expectedSource2)53 val tilsammen = source1 + source254 tilsammen.shouldNotBeNull()55 tilsammen.results().size shouldBe (source1.results().size + source2.results().size)56 tilsammen.results().shouldBeEmpty()57 tilsammen.failedSources().size shouldBe (source1.failedSources().size + source2.failedSources().size)58 tilsammen.successFullSources().size shouldBe 059 tilsammen.hasErrors() shouldBe true60 tilsammen.failedSources() shouldBe listOf(expectedSource1, expectedSource2)61 tilsammen.determineHttpCode() shouldBe HttpStatusCode.ServiceUnavailable62 }63 @Test64 fun `Skal kunne addere et tomt resultatobjekt for beskjed til et annet resultat uten at resultatet endrer seg`() {65 val expectedSource1 = KildeType.EVENTHANDLER66 val validResult = MultiSourceResultObjectMother.giveMeNumberOfSuccessfulBeskjedEventsForSource(1, expectedSource1)67 val emptyBeskjedResult = MultiSourceResult.createEmptyResult<BeskjedDTO>()68 val sum = validResult + emptyBeskjedResult69 sum.shouldNotBeNull()70 sum.results().size shouldBe validResult.results().size71 sum.results() shouldBe validResult.results()72 sum.failedSources().size shouldBe validResult.failedSources().size73 sum.successFullSources().size shouldBe validResult.successFullSources().size74 sum.successFullSources() shouldContain expectedSource175 sum.hasErrors() shouldBe false76 sum.determineHttpCode() shouldBe HttpStatusCode.OK77 }78 @Test79 fun `Skal kunne addere et tomt resultatobjekt for oppgave til et annet resultat uten at resultatet endrer seg`() {80 val expectedSource1 = KildeType.EVENTHANDLER81 val validResult = MultiSourceResultObjectMother.giveMeNumberOfSuccessfulOppgaveEventsForSource(1, expectedSource1)82 val emptyBeskjedResult = MultiSourceResult.createEmptyResult<OppgaveDTO>()83 val sum = validResult + emptyBeskjedResult84 sum.shouldNotBeNull()85 sum.results().size shouldBe validResult.results().size86 sum.results() shouldBe validResult.results()87 sum.failedSources().size shouldBe validResult.failedSources().size88 sum.successFullSources().size shouldBe validResult.successFullSources().size89 sum.successFullSources() shouldContain expectedSource190 sum.hasErrors() shouldBe false91 sum.determineHttpCode() shouldBe HttpStatusCode.OK92 }93}...
MainViewModelTest.kt
Source:MainViewModelTest.kt
1package hu.bme.aut.recipebase.ui2import android.app.Application3import com.google.common.truth.Truth4import hu.bme.aut.recipebase.ViewModelTestListener5import hu.bme.aut.recipebase.createNetworkRecipe6import hu.bme.aut.recipebase.network.model.RecipeList7import hu.bme.aut.recipebase.ui.activity.main.MainRepository8import hu.bme.aut.recipebase.ui.activity.main.MainViewModel9import hu.bme.aut.recipebase.ui.state.UiState10import io.kotest.assertions.timing.eventually11import io.kotest.core.spec.style.StringSpec12import io.kotest.core.spec.style.Test13import io.kotest.core.test.TestCase14import io.kotest.matchers.shouldBe15import io.mockk.*16import kotlinx.coroutines.ExperimentalCoroutinesApi17import kotlinx.coroutines.delay18import kotlinx.coroutines.launch19import java.lang.Exception20import kotlin.time.DurationUnit21import kotlin.time.toDuration22@ExperimentalCoroutinesApi23@Test24class MainViewModelTest : StringSpec({25 val application: Application = mockk()26 val repository: MainRepository = mockk()27 val recipeList = RecipeList()28 .addResultsItem(createNetworkRecipe(id = 1, name = "Test 1"))29 .addResultsItem(createNetworkRecipe(id = 2, name = "Test 2"))30 .addResultsItem(createNetworkRecipe(id = 3, name = "Test 3"))31 "init should refresh the UiState and get first 20 recipes from repository when initially fetching data" {32 coEvery {33 repository.fetchRecipes(34 from = 0,35 size = 20,36 query = "",37 )38 } returns recipeList39 //val viewModel = MainViewModel(application, repository)40 //viewModel.uiState.value shouldBe UiState.Loading41 //viewModel.uiState.value shouldBe UiState.Loaded42 /*eventually(duration = 2L.toDuration(DurationUnit.SECONDS)) { // duration in millis43 viewModel.uiState.value shouldBe UiState.Loaded44 }*/45 /* val viewModel = MainViewModel(application, repository)46 assertEquals(true, viewModel.uiState.value is UiState.Loading)47 delay(1000)48 assertEquals(true, viewModel.uiState.value is UiState.Loaded)49 verify { viewModel.init() }50 verify { viewModel.onRecipesFetched() }*/51 }52 "if load failed, UiState should change to Error" {53 coEvery {54 repository.fetchRecipes(55 from = 0,56 size = MainViewModel.FETCH_SIZE,57 query = "",58 )59 } throws Exception("e")60 val viewModel = MainViewModel(application, repository)61 viewModel.init()62 assert(viewModel.uiState.value is UiState.Error)63 }64 "search recipes should get recipes from repository" {65 coEvery {66 repository.fetchRecipes(67 query = "Test",68 from = 0,69 size = MainViewModel.FETCH_SIZE,70 )71 } returns recipeList72 val viewModel = MainViewModel(application, repository)73 viewModel.updateSearchTextState("Test")74 viewModel.searchRecipes {}75 coVerify {76 repository.fetchRecipes(77 query = "Test",78 from = 0,79 size = MainViewModel.FETCH_SIZE,80 )81 }82 //verify { viewModel.onRecipesFetched() }83 assert(!viewModel.centerLoadingState.value)84 }85 "delete recipe should refresh the list after deletion" {86 coEvery { repository.deleteRecipe(id = 1) } returns Unit87 coEvery {88 repository.fetchRecipes(89 from = 0,90 size = 20,91 query = "",92 )93 } returns recipeList94 val viewModel = MainViewModel(application, repository)95 viewModel.deleteRecipe(createNetworkRecipe(id = 1, name = "Test name")) {}96 coVerify { repository.deleteRecipe(id = 1) }97 verify { viewModel.onRecipeDeleted() }98 assert(!viewModel.centerLoadingState.value)99 }100 "add to favorite should refresh the list of favorites" {101 coEvery {102 repository.writeFavorite(103 createNetworkRecipe(104 id = 1,105 name = "Test name"106 )107 )108 } returns Unit109 val viewModel = MainViewModel(application, repository)110 viewModel.addToFavorite(createNetworkRecipe(id = 1, name = "Test name")) {}111 coVerify { repository.writeFavorite(createNetworkRecipe(id = 1, name = "Test name")) }112 Truth.assertThat(viewModel.favoriteListState.value)113 .containsExactly(createNetworkRecipe(id = 1, name = "Test name"))114 assert(!viewModel.centerLoadingState.value)115 }116 "delete from favorite should refresh the list of favorites" {117 coEvery { repository.deleteRecipe(id = 1) } returns Unit118 val viewModel = MainViewModel(application, repository)119 viewModel.deleteFromFavorite(createNetworkRecipe(id = 1, name = "Test name")) {}120 //coVerify { repository.deleteRecipe(id = 1) }121 assert(!viewModel.centerLoadingState.value)122 }123}) {124 init {125 listener(ViewModelTestListener())126 }127 override fun beforeTest(testCase: TestCase) {128 super.beforeTest(testCase)129 clearAllMocks()130 }131}...
ConfirmationDataSourceTest.kt
Source:ConfirmationDataSourceTest.kt
...44 val value = Mocks.accountsFromValidator(paginationTwenty)45 coEvery { getDataSource.accountsFromValidator(paginationTwenty) } returns Outcome.Success(value)46 val response = confirmationDataSource.fetchAccounts(paginationTwenty)47 check(response is Outcome.Success)48 response.value.results.shouldNotBeEmpty()49 response.value.count shouldBeGreaterThan 2050 response.value.results.size shouldBeLessThanOrEqual 2051 }52 @Test53 fun `should fetch list of 30 accounts successfully`() = runBlockingTest {54 val value = Mocks.accountsFromValidator(paginationThirty)55 coEvery { getDataSource.accountsFromValidator(paginationThirty) } returns Outcome.Success(value)56 val response = confirmationDataSource.fetchAccounts(paginationThirty)57 check(response is Outcome.Success)58 response.value.results.shouldNotBeEmpty()59 response.value.count shouldBeGreaterThan 060 response.value.results.size shouldBeLessThanOrEqual 3061 }62 }63 }64 @Nested65 @DisplayName("Given request that should fail")66 @TestInstance(TestInstance.Lifecycle.PER_CLASS)67 inner class GivenFailingRequest {68 private val pagination = Mocks.paginationOptionsDefault()69 @Nested70 @DisplayName("When performing a GET request...")71 @TestInstance(TestInstance.Lifecycle.PER_CLASS)72 inner class WhenGetRequest {73 @Test74 fun `should return error outcome for list of accounts from primary validator IOException`() = runBlockingTest {...
Thread_01_ExecutorServiceTests.kt
Source:Thread_01_ExecutorServiceTests.kt
...36 parallelism shouldBeGreaterThan 0 // >= 037 }38 }39 `when`("모ë ìì
ì´ ì ì ì¢
ë£ ë ê²½ì°") {40 val results = es.invokeAll(arrayListOf(task1, task2, task3, task4), timeoutSec.toLong(), TimeUnit.SECONDS)41 shutdown(es)42 for (result in results) {43 logger.info("[TEST] member seq : ${result.get()}")44 }45 then("ìì
ëª©ë¡ size ê° task ê°ìì ê°ìì¼ íë¤."){46 results.size shouldBe 4 // >= 0\47 }48 }49 `when`("íìììì 1ì´ë¡ ì¤ì íì¬ ì´ê³¼ ë ê²½ì°" ) {50 timeoutSec = 151 try {52 val results = es.invokeAll(arrayListOf(task1, task2, task3, task4), timeoutSec.toLong(), TimeUnit.SECONDS)53 shutdown(es)54 for (result in results) {55 logger.info("[TEST] member seq : ${result.get()}")56 }57 } catch (e: CancellationException) {58 es.shutdownNow()59 exception = e.toString()60 }61 then("exception message ê° ì ì ì¶ë ¥ëì´ì¼ íë¤."){62 logger.info("[TEST] exception message -> $exception")63 exception.length shouldBeGreaterThan 0 // >= 064 }65 }66 }67 }68 fun shutdown(es : ExecutorService){...
SearchFacadeTest.kt
Source:SearchFacadeTest.kt
...51 val reply4 = db.insert(post(thread1, postNumber = 6L, body = "Another unrelated reply"))52 }53 searchFacade.searchPosts("first~1").should {54 it.totalResultsCount shouldBe 355 it.resultsCount shouldBe 356 it.resultList.map(PostDto::getPostNumber).shouldContainExactlyInAnyOrder(1L, 4L, 5L)57 it.resultList.map(PostDto::getBody)58 .all { body -> body.contains(Constants.SEARCH_RESULT_HIGHLIGHT_START) && body.contains(Constants.SEARCH_RESULT_HIGHLIGHT_END) }59 .shouldBeTrue()60 }61 }62}...
build.gradle.kts
Source:build.gradle.kts
...36 testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")37}38tasks.named<Test>("test") { // or "jvmTest" etc39 useJUnitPlatform()40 systemProperty("allure.results.directory", project.buildDir.toString() + "/allure-results")41}...
ManagerTest.kt
Source:ManagerTest.kt
...34 )35 manager.start()36 latch.await(5, TimeUnit.SECONDS)37 then("I could move from state to state") {38 val results = outputs.map { it.raw }39 val correct = taskInputs.map { Fibonacci.count(it) }40 results shouldBe correct41 }42 }43})...
results
Using AI Code Generation
1results.test("my test") {2}3results.test("my test") {4}5results.test("my test") {6}7results.test("my test") {8}9results.test("my test") {10}11results.test("my test") {12}13results.test("my test") {14}15results.test("my test") {16}17results.test("my test") {18}19results.test("my test") {20}21results.test("my test") {22}23results.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!!