Best Kotest code snippet using io.kotest.core.TestConfiguration.afterEach
TestConfiguration.kt
Source:TestConfiguration.kt
...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) {202 f(Tuple2(testCase, result))203 }204 })205 }206 /**207 * Registers a callback to be executed before every [TestCase]208 * with type [TestType.Test] or [TestType.Container].209 *210 * The [TestCase] about to be executed is provided as the parameter.211 */212 fun beforeAny(f: BeforeAny) {213 register(object : TestListener {214 override suspend fun beforeAny(testCase: TestCase) {215 f(testCase)...
FileControllerTest.kt
Source:FileControllerTest.kt
1package com.github.afezeria.hymn.oss.web.controller2import com.github.afezeria.hymn.common.BaseDbTest3import com.github.afezeria.hymn.common.TestApplication4import com.github.afezeria.hymn.common.adminSession5import com.github.afezeria.hymn.common.platform.OssService6import com.github.afezeria.hymn.common.platform.Session7import com.github.afezeria.hymn.common.testconfiguration.RedisTestConfig8import com.github.afezeria.hymn.common.util.toClass9import com.github.afezeria.hymn.oss.OssTestConfiguration10import com.github.afezeria.hymn.oss.contentType2Bucket11import com.github.afezeria.hymn.oss.filename2ContentType12import com.github.afezeria.hymn.oss.module.service.FileRecordService13import io.kotest.assertions.assertSoftly14import io.kotest.matchers.shouldBe15import io.kotest.matchers.shouldNotBe16import io.kotest.matchers.string.shouldMatch17import io.mockk.every18import io.mockk.mockkObject19import io.mockk.unmockkAll20import okhttp3.OkHttpClient21import okhttp3.Request22import org.junit.jupiter.api.AfterAll23import org.junit.jupiter.api.AfterEach24import org.junit.jupiter.api.BeforeEach25import org.junit.jupiter.api.Test26import org.springframework.beans.factory.annotation.Autowired27import org.springframework.boot.test.context.SpringBootTest28import org.springframework.boot.test.web.client.TestRestTemplate29import org.springframework.boot.web.server.LocalServerPort30import org.springframework.core.io.FileSystemResource31import org.springframework.http.HttpEntity32import org.springframework.http.HttpHeaders33import org.springframework.http.MediaType34import org.springframework.util.LinkedMultiValueMap35import org.springframework.util.MultiValueMap36import java.io.ByteArrayInputStream37import java.io.File38import java.nio.file.Files39import java.nio.file.Path40import java.nio.file.StandardOpenOption41import java.time.LocalDateTime42/**43 * @author afezeria44 */45@SpringBootTest(46 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,47 classes = [TestApplication::class, OssTestConfiguration::class, RedisTestConfig::class],48)49internal class FileControllerTest : BaseDbTest() {50 companion object {51 @AfterAll52 @JvmStatic53 fun after() {54 Files.walk(Path.of(System.getProperty("user.dir") + "/hymn_storage")).use { walk ->55 walk.sorted(Comparator.reverseOrder())56 .map { obj: Path -> obj.toFile() }57 .peek { println("delete $it") }58 .forEach(File::delete)59 }60 }61 }62 @LocalServerPort63 var port: Int = -164 @Autowired65 lateinit var restTemplate: TestRestTemplate66 @Autowired67 lateinit var fileRecordService: FileRecordService68 @BeforeEach69 fun setUp() {70 mockkObject(Session.Companion)71 every { Session.getInstance() } returns adminSession72 }73 @AfterEach74 fun tearDown() {75 unmockkAll()76 }77 @Autowired78 lateinit var ossService: OssService79 @Autowired80 lateinit var client: OkHttpClient81 @Test82 fun tmpFileUpload() {83 val now = LocalDateTime.now()84 val requestEntity = createRequestEntity()85 val serverUrl = "http://localhost:$port/module/oss/api/tmp-file"86 val resp = restTemplate.postForEntity(serverUrl, requestEntity, String::class.java)87 resp.statusCodeValue shouldBe 20088 resp.body!!.length shouldBe 3289 val filename = (requestEntity.body!!.get("file")!!.get(0) as FileSystemResource).filename90 val contentType = filename2ContentType(filename)91 val bucket = contentType2Bucket(contentType)92 val fileRecord = fileRecordService.findById(resp.body!!)!!93 fileRecord shouldNotBe null94 fileRecord.contentType shouldBe contentType95 fileRecord.bucket shouldBe bucket96 fileRecord.path shouldMatch "${now.year}/${now.monthValue}/${now.dayOfMonth}/.*?$filename".toRegex()97 fileRecord.tmp shouldBe true98 }99 @Test100 fun `upload empty tmp file`() {101 val requestEntity = createRequestEntity(ByteArray(0))102 val serverUrl = "http://localhost:$port/module/oss/api/tmp-file"103 val resp = restTemplate.postForEntity(serverUrl, requestEntity, String::class.java)104 resp.statusCodeValue shouldBe 400105 resp.body shouldNotBe null106 resp.body.toClass<Map<String, String>>()!!.get("message") shouldBe "ä¸ä¼ æ件å
容为空"107 }108 @Test109 fun fileUpload() {110 val now = LocalDateTime.now()111 val requestEntity = createRequestEntity()112 val serverUrl = "http://localhost:$port/module/oss/api/file"113 val resp = restTemplate.postForEntity(serverUrl, requestEntity, String::class.java)114 resp.statusCodeValue shouldBe 200115 resp.body!!.length shouldBe 32116 val filename = (requestEntity.body!!.get("file")!!.get(0) as FileSystemResource).filename117 val contentType = filename2ContentType(filename)118 val bucket = contentType2Bucket(contentType)119 val fileRecord = fileRecordService.findById(resp.body!!)!!120 fileRecord shouldNotBe null121 fileRecord.contentType shouldBe contentType122 fileRecord.bucket shouldBe bucket123 fileRecord.path shouldMatch "${now.year}/${now.monthValue}/${now.dayOfMonth}/.*?$filename".toRegex()124 fileRecord.tmp shouldBe false125 }126 @Test127 fun download() {128 val bucket = "other"129 val path = "2021/01/01/abc.txt"130 val fileId = ossService.putObject(131 bucket = bucket,132 objectName = path,133 inputStream = ByteArrayInputStream("abc".toByteArray()),134 contentType = "application/octet-stream",135 tmp = false136 )137 val url = "http://localhost:$port/module/oss/api/file/$fileId"138 val request = Request.Builder().url(url).build()139 client.newCall(request).execute().use {140 val body = it.body()?.string()141 assertSoftly {142 it.code() shouldBe 200143 body shouldNotBe null144 body shouldBe "abc"145 it.header("Content-Disposition") shouldBe "attachment;filename=\"abc.txt\""146 }147 }148 }149 fun createRequestEntity(150 content: ByteArray? = null,151 suffix: String? = null152 ): HttpEntity<MultiValueMap<String, Any>> {153 val headers = HttpHeaders()154 val tmp = Files.createTempFile("abc", suffix ?: ".txt")155 Files.write(tmp, content ?: "abc".toByteArray(), StandardOpenOption.WRITE)156 headers.contentType = MediaType.MULTIPART_FORM_DATA157 val body: MultiValueMap<String, Any> = LinkedMultiValueMap()158 body.add("file", FileSystemResource(tmp))159 return HttpEntity(body, headers)160 }161}...
SavePersonConfigurationFunTest.kt
Source:SavePersonConfigurationFunTest.kt
...17class SavePersonConfigurationFunTest(18 private val jobLauncherTestUtils: JobLauncherTestUtils,19 private val personRepository: PersonRepository20): FunSpec({21 afterEach {22 personRepository.deleteAll()23 }24// test("stepì ëí´ì í
ì¤í¸ë¥¼ ì§íí ì ìë¤.") {25// val launchStep = jobLauncherTestUtils.launchStep("savePersonStep")26//27// launchStep.stepExecutions.sumOf { it.writeCount } shouldBe 328// }29 test("ì´ë¦ ì¤ë³µì íë½íì§ ìì¼ë©´ Personì 3ëª
ì ì¥íë¤") {30 val jobParameters = JobParametersBuilder()31 .addString("allow_duplicate", "false")32 .toJobParameters()33 // when34 val jobExecution = jobLauncherTestUtils.launchJob(jobParameters)35 // then...
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
...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
...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}...
AccountConfigurationTest.kt
Source:AccountConfigurationTest.kt
...9class AccountConfigurationTest(10 private val jobLauncherTestUtils: JobLauncherTestUtils,11 private val accountRepo: AccountRepository12) : FunSpec({13// afterEach {14// accountRepo.deleteAll()15// }16 test("í
ì¤í¸") {17 val jobExecution = jobLauncherTestUtils.launchJob()18 val size = accountRepo.findAllByUpdatedDate(LocalDate.now()).size19 val actual = jobExecution.stepExecutions20 .filter { it.stepName == "userLevelUpStep" }21 .sumOf { it.writeCount }22 actual shouldBe size23 actual shouldBe 30024 accountRepo.count() shouldBe 40025 }26})...
Memo.kt
Source:Memo.kt
...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}...
afterEach
Using AI Code Generation
1fun afterEach() {2println("After each test")3}4fun afterProject() {5println("After all tests")6}7}
afterEach
Using AI Code Generation
1fun afterTest() {2println("After Test")3}4fun afterAllTests() {5println("After All Tests")6}7fun beforeAllTests() {8println("Before All Tests")9}10fun afterSpec() {11println("After Spec")12}13fun beforeSpec() {14println("Before Spec")15}16}
afterEach
Using AI Code Generation
1import io.kotest.core.spec.style.FunSpec2class TestConfigurationExample : FunSpec({3test("test 1") {4}5test("test 2") {6}7test("test 3") {8}9})
afterEach
Using AI Code Generation
1import io.kotest.core.spec.style.FunSpec2class ExampleSpec : FunSpec({3})4import io.kotest.core.spec.style.FunSpec5class ExampleSpec : FunSpec({6 beforeSpec {7 println("This is called before the spec")8 }9 afterSpec {10 println("This is called after the spec")11 }12 test("This is a test") {13 println("This is a test")14 }15})16import io.kotest.core.spec.style.FunSpec17class ExampleSpec : FunSpec({18 beforeEach {19 println("This is called before each test")20 }21 afterEach {22 println("This is called after each test")23 }24 test("This is a test") {25 println("This is a test")26 }27})28import io.kotest.core.spec.style.FunSpec29class ExampleSpec : FunSpec({30 beforeTest {31 println("This is called before each test")32 }33 afterTest {34 println("This is called after each test")35 }36 test("This is a test") {37 println("This is a test")38 }39})
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!!