Best Kotest code snippet using io.kotest.core.TestConfiguration.beforeEach
TestConfiguration.kt
Source:TestConfiguration.kt
...181 * with type [TestType.Test].182 *183 * The [TestCase] about to be executed is provided as the parameter.184 */185 fun beforeEach(f: BeforeEach) {186 register(object : TestListener {187 override suspend fun beforeEach(testCase: TestCase) {188 f(testCase)189 }190 })191 }192 /**193 * Registers a callback to be executed after every [TestCase]194 * with type [TestType.Test].195 *196 * The callback provides two parameters - the test case that has just completed,197 * and the [TestResult] outcome of that test.198 */199 fun afterEach(f: AfterEach) {200 register(object : TestListener {201 override suspend fun afterEach(testCase: TestCase, result: TestResult) {...
TaskControllerTest.kt
Source:TaskControllerTest.kt
1package com.pavan.tasktracker.controller2import com.pavan.tasktracker.model.Task3import com.pavan.tasktracker.service.TaskService4import io.kotest.assertions.assertSoftly5import io.kotest.extensions.time.withConstantNow6import io.kotest.matchers.shouldBe7import io.mockk.every8import io.mockk.mockk9import org.junit.jupiter.api.BeforeEach10import org.junit.jupiter.api.Test11import org.springframework.beans.factory.annotation.Autowired12import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest13import org.springframework.boot.test.context.TestConfiguration14import org.springframework.context.annotation.Bean15import org.springframework.context.annotation.Import16import org.springframework.test.web.reactive.server.WebTestClient17import reactor.core.publisher.Flux18import reactor.core.publisher.Mono19import java.time.LocalDateTime20@WebFluxTest(TaskController::class)21@Import(value = [TaskControllerTest.ControllerTestConfig::class])22class TaskControllerTest(23 @Autowired val webTestClient: WebTestClient,24 @Autowired val taskService: TaskService25) {26 @BeforeEach27 fun setUp() {28 every { taskService.getTasks() } returns Flux.just(29 Task(30 id = 1,31 name = "name",32 description = "SomeValue",33 createdDate = LocalDateTime.now(),34 startDate = null,35 finishDate = null36 ), Task(37 id = 2,38 name = "name",39 description = "SomeValue",40 createdDate = LocalDateTime.now(),41 startDate = null,42 finishDate = null43 )44 )45 }46 @Test47 fun `should return count of tasks`() {48 val response = webTestClient.get()49 .uri("/api/tasks")50 .exchange()51 .expectStatus().isOk52 .expectBodyList(Task::class.java)53 .returnResult()54 .responseBody!!55 response.size shouldBe 256 }57 @Test58 fun `should return task by task id 1`() {59 every { taskService.getTaskById(any()) } returns Mono.just(60 Task(61 id = 1,62 name = "task name",63 description = "task description",64 createdDate = LocalDateTime.now(),65 startDate = null,66 finishDate = null67 )68 )69 val taskResponse = webTestClient.get()70 .uri("/api/tasks/1")71 .exchange()72 .expectStatus().isOk73 .expectBody(Task::class.java)74 .returnResult()75 .responseBody!!76 assertSoftly {77 taskResponse.id shouldBe 178 }79 }80 @Test81 fun `Task should contain id,name,description,createdDate,startDate,finishDate`() {82 val now = LocalDateTime.now()83 withConstantNow(now) {84 every { taskService.getTaskById(any()) } returns Mono.just(85 Task(86 id = 1,87 name = "task name",88 description = "task description",89 createdDate = LocalDateTime.now(),90 startDate = null,91 finishDate = null92 )93 )94 val taskResponse = webTestClient.get()95 .uri("/api/tasks/1")96 .exchange()97 .expectStatus().isOk98 .expectBody(Task::class.java)99 .returnResult()100 .responseBody!!101 assertSoftly {102 taskResponse.id shouldBe 1103 taskResponse.name shouldBe "task name"104 taskResponse.description shouldBe "task description"105 taskResponse.createdDate shouldBe now106 taskResponse.startDate shouldBe null107 taskResponse.finishDate shouldBe null108 }109 }110 }111 @TestConfiguration112 class ControllerTestConfig {113 @Bean114 fun taskService() = mockk<TaskService>()115 }116}...
PostgresFileArchiverStorageFunTest.kt
Source:PostgresFileArchiverStorageFunTest.kt
...51class PostgresFileArchiverStorageFunTest : WordSpec({52 val postgresListener = PostgresListener()53 lateinit var storage: PostgresFileArchiverStorage54 register(postgresListener)55 beforeEach {56 storage = PostgresFileArchiverStorage(postgresListener.dataSource)57 }58 "hasArchive()" should {59 "return false when no archive for the given provenance has been added" {60 storage.hasArchive(VCS_PROVENANCE) shouldBe false61 }62 "return true when an archive for the given provenance has been added" {63 storage.addArchive(VCS_PROVENANCE, writeTempFile("content"))64 storage.hasArchive(VCS_PROVENANCE) shouldBe true65 }66 }67 "getArchive()" should {68 "return the archives corresponding to the given provenance given such archive has been added" {69 storage.addArchive(VCS_PROVENANCE, writeTempFile("VCS"))...
PostgresMealRepositoryReadTest.kt
Source:PostgresMealRepositoryReadTest.kt
1package com.stringconcat.ddd.shop.persistence.postgresql2import com.stringconcat.ddd.shop.domain.mealId3import com.stringconcat.ddd.shop.domain.mealName4import io.kotest.matchers.collections.shouldBeEmpty5import io.kotest.matchers.collections.shouldHaveSize6import io.kotest.matchers.nulls.shouldBeNull7import io.kotest.matchers.nulls.shouldNotBeNull8import javax.sql.DataSource9import org.junit.jupiter.api.BeforeEach10import org.junit.jupiter.api.Test11import org.springframework.beans.factory.annotation.Autowired12import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate13import org.springframework.test.context.junit.jupiter.SpringJUnitConfig14@SpringJUnitConfig(classes = [TestConfiguration::class])15class PostgresMealRepositoryReadTest {16 @Autowired17 private lateinit var dataSource: DataSource18 @Autowired19 private lateinit var jdbcTemplate: NamedParameterJdbcTemplate20 @BeforeEach21 fun before() {22 cleanMealTable(jdbcTemplate)23 }24 @Test25 fun `get by id - not found`() {26 val repository = PostgresMealRepository(dataSource, MockEventPublisher())27 val result = repository.getById(mealId())28 result.shouldBeNull()29 }30 @Test31 fun `get by id - successfully returned`() {32 val meal = newMeal()33 val repository = PostgresMealRepository(dataSource, MockEventPublisher())34 repository.save(meal)35 val result = repository.getById(meal.id)36 result.shouldNotBeNull()37 result.checkEquals(meal)38 }39 @Test40 fun `get by name - not found`() {41 val repository = PostgresMealRepository(dataSource, MockEventPublisher())42 val result = repository.getByName(mealName())43 result.shouldBeNull()44 }45 @Test46 fun `get by name - successfully returned`() {47 val meal = newMeal()48 val repository = PostgresMealRepository(dataSource, MockEventPublisher())49 repository.save(meal)50 val result = repository.getByName(meal.name)51 result.shouldNotBeNull()52 result.checkEquals(meal)53 }54 @Test55 fun `get all - table is empty`() {56 cleanMealTable(jdbcTemplate)57 val repository = PostgresMealRepository(dataSource, MockEventPublisher())58 val result = repository.getAll()59 result.shouldBeEmpty()60 }61 @Test62 fun `get all - table is not empty`() {63 val meal = newMeal()64 val repository = PostgresMealRepository(dataSource, MockEventPublisher())65 repository.save(meal)66 val result = repository.getAll()67 result.shouldHaveSize(1)68 result[0].checkEquals(meal)69 }70 @Test71 fun `get all - table is not empty but only removed`() {72 val meal = newMeal()73 meal.removeMealFromMenu()74 val repository = PostgresMealRepository(dataSource, MockEventPublisher())75 repository.save(meal)76 val result = repository.getAll()77 result.shouldBeEmpty()78 }79}...
DeviceServiceTest.kt
Source:DeviceServiceTest.kt
1package vvu.study.kotlin.demo.services.devices2import com.ninjasquad.springmockk.MockkBean3import io.kotest.common.runBlocking4import io.kotest.matchers.shouldBe5import io.kotest.matchers.types.shouldBeSameInstanceAs6import io.mockk.every7import io.mockk.mockk8import io.mockk.slot9import io.mockk.verify10import org.junit.jupiter.api.AfterEach11import org.junit.jupiter.api.BeforeEach12import org.junit.jupiter.api.Test13import org.junit.jupiter.api.Assertions.*14import org.junit.jupiter.api.extension.ExtendWith15import org.springframework.beans.factory.annotation.Autowired16import org.springframework.boot.test.context.SpringBootTest17import org.springframework.boot.test.context.TestConfiguration18import org.springframework.boot.test.mock.mockito.MockBean19import org.springframework.context.annotation.Bean20import org.springframework.test.context.junit.jupiter.SpringExtension21import reactor.core.publisher.Flux22import reactor.core.publisher.Mono23import vvu.study.kotlin.demo.ds.repos.inf.DeviceRepo24import vvu.study.kotlin.demo.dtos.Device25import vvu.study.kotlin.demo.dtos.utils.DeviceUtils26import java.time.LocalDateTime27import java.time.ZoneOffset28import java.time.temporal.ChronoUnit29import java.util.*30@ExtendWith(SpringExtension::class)31@SpringBootTest( classes = [ DeviceService::class ])32internal class DeviceServiceTest {33 @Autowired34 lateinit var service: DeviceService35 @MockkBean36 lateinit var deviceRepo : DeviceRepo37 @Test38 fun `Create a Device`() = runBlocking {39 val device = DeviceUtils.createADevice()40 val slotDevice = slot<Device>()41 val id = UUID.randomUUID().toString()42 every {43 deviceRepo.create( capture(slotDevice))44 } returns Mono.just( id )45 val newId = service.create( device )46 verify(exactly = 1) {47 deviceRepo.create(any())48 }49 slotDevice.captured shouldBeSameInstanceAs device50 newId shouldBe id51 }52}...
setup.kt
Source:setup.kt
...27 "/migrations.sql"28 )!!.toURI()29).readText().split("\n\n")30fun TestConfiguration.useDatabase() {31 beforeEach {32 transaction {33 SchemaUtils.createSchema(Schema("public"))34 migrationsSql.forEach { TransactionManager.current().exec(it) }35 }36 }37 afterEach {38 transaction {39 SchemaUtils.dropSchema(Schema("public"), cascade = true)40 }41 }42}...
ExtensionsTest.kt
Source:ExtensionsTest.kt
...18 }19 override suspend fun beforeSpec(spec: Spec) {20 testConfiguration.git.repo.directory.toFile().deleteRecursively()21 }22 override suspend fun beforeEach(testCase: TestCase) {23 testRepo()24 }25 override suspend fun afterEach(testCase: TestCase, result: TestResult) {26 testConfiguration.git.repo.directory.toFile().deleteRecursively()27 }28}...
Memo.kt
Source:Memo.kt
...7 destructor: (T) -> Unit = {},8 factory: () -> T,9): ReadOnlyProperty<Nothing?, T> {10 var value: Any? = NOT_INITIALIZED11 beforeEach {12 value = factory()13 }14 afterEach {15 destructor(value as T)16 value = NOT_INITIALIZED17 }18 return ReadOnlyProperty { _, _ ->19 value as T20 }21}
beforeEach
Using AI Code Generation
1override fun beforeSpec(spec: Spec) {2println("beforeSpec: $spec")3}4override fun beforeTest(testCase: TestCase) {5println("beforeTest: $testCase")6}7override fun afterSpec(spec: Spec) {8println("afterSpec: $spec")9}10override fun afterTest(testCase: TestCase, result: TestResult) {11println("afterTest: $testCase, $result")12}13}14override fun afterSpec(spec: Spec) {15println("afterSpec: $spec")16}17override fun afterTest(testCase: TestCase, result: TestResult) {18println("afterTest: $testCase, $result")19}20}21override fun afterSpec(spec: Spec) {22println("afterSpec: $spec")23}24}25override fun afterTest(testCase: TestCase, result: TestResult) {26println("afterTest: $testCase, $result")27}28}29override fun afterProject() {30println("afterProject")31}32}33override fun afterContainer(testCase: TestCase, result: TestResult) {34println("afterContainer: $testCase, $result")35}36}37override fun afterInvocation(testCase: TestCase, result: TestResult) {38println("afterInvocation: $testCase, $result")39}40}41override fun beforeContainer(testCase: TestCase) {42println("beforeContainer: $testCase")43}44}45override fun beforeInvocation(testCase: TestCase) {46println("beforeInvocation: $testCase")47}48}49override fun beforeProject() {50println("beforeProject")51}52}53override fun beforeSpec(spec: Spec) {54println("beforeSpec: $spec")55}56}
beforeEach
Using AI Code Generation
1val config = TestConfiguration()2config.beforeEach {3println("Before each test")4}5config.afterEach {6println("After each test")7}8config.afterAll {9println("After all test")10}11config.beforeAll {12println("Before all test")13}14config.afterSpec {15println("After spec")16}17config.beforeSpec {18println("Before spec")19}20config.afterProject {21println("After project")22}23config.beforeProject {24println("Before project")25}26val spec = describe("Sample Test") {27context("Sample Test") {28it("Sample Test") {29println("Sample Test")30}31}32}33spec.test()34val config = TestConfiguration()35config.beforeEach {36println("Before each test")37}38config.afterEach {39println("After each test")40}41config.afterAll {42println("After all test")43}44config.beforeAll {45println("Before all test")46}47config.afterSpec {48println("After spec")49}50config.beforeSpec {51println("Before spec")52}53config.afterProject {54println("After project")55}56config.beforeProject {57println("Before project")58}59val spec = describe("Sample Test") {60context("Sample Test") {61it("Sample Test") {62println("Sample Test")63}64}65}66spec.test()67val config = TestConfiguration()68config.beforeEach {69println("Before each test")70}71config.afterEach {72println("After each test")73}74config.afterAll {75println("After all test")76}77config.beforeAll {78println("Before all test")79}80config.afterSpec {81println("After spec")82}83config.beforeSpec {84println("Before spec")85}86config.afterProject {87println("After project")88}89config.beforeProject {90println("Before project")91}92val spec = describe("Sample Test") {93context("Sample Test") {94it("Sample Test") {95println("Sample Test")96}97}98}99spec.test()100val config = TestConfiguration()101config.beforeEach {102println("Before each test")103}104config.afterEach {105println("After each test")106}107config.afterAll {108println("After all test")109}110config.beforeAll {111println("Before all test")112}113config.afterSpec {114println("After spec")115}116config.beforeSpec {117println("Before spec")
beforeEach
Using AI Code Generation
1@TestInstance(TestInstance.Lifecycle.PER_CLASS)2class TestConfigurationTest {3fun beforeEach() {4}5fun test1() {6}7fun test2() {8}9}10@TestInstance(TestInstance.Lifecycle.PER_CLASS)11class TestConfigurationTest {12fun afterEach() {13}14fun test1() {15}16fun test2() {17}18}19@TestInstance(TestInstance.Lifecycle.PER_CLASS)20class TestConfigurationTest {21fun beforeSpec() {22}23fun test1() {24}25fun test2() {26}27}28@TestInstance(TestInstance.Lifecycle.PER_CLASS)29class TestConfigurationTest {30fun afterSpec() {31}32fun test1() {33}34fun test2() {35}36}37@TestInstance(TestInstance.Lifecycle.PER_CLASS)38class TestConfigurationTest {39fun beforeTest() {40}41fun test1() {42}43fun test2() {44}45}46@TestInstance(TestInstance.Lifecycle.PER_CLASS)47class TestConfigurationTest {48fun afterTest() {49}50fun test1() {51}52fun test2() {53}54}55@TestInstance(TestInstance.Lifecycle.PER_CLASS)56class TestConfigurationTest {57fun beforeProject() {58}59fun test1() {60}61fun test2() {
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!!