1. JUnit 5 kotlin import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertEquals class MyTest { @Test fun myTestMethod() { val result = 2 + 2 assertEquals(4, result) } } 2. Spek kotlin import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature object MySpec : Spek({ Feature("Calculator") { Scenario("Adding two numbers") { val calculator = Calculator() Given("two numbers") { val a = 2 val b = 3 } When("adding them") { calculator.add(a, b) } Then("the result should be their sum") { assertEquals(5, calculator.result) } } } }) 3. Kotest kotlin import io.kotest.core.spec.style.BehaviorSpec import io.kotest.matchers.shouldBe class MyTest : BehaviorSpec() { init { given("two numbers") { val a = 2 val b = 3 `when`("adding them") { val result = a + b then("the result should be their sum") { result shouldBe 5 } } } } } 4. MockK kotlin import io.mockk.every import io.mockk.mockk import io.mockk.verify interface UserRepository { fun getUser(id: String): User } class UserService(private val userRepository: UserRepository) { fun getUserByUsername(username: String): User? { val user = userRepository.getUser(username) return if (user.username == username) user else null } } class UserServiceTest { private val userRepository: UserRepository = mockk() private val userService = UserService(userRepository) @Test fun testGetUserByUsername() { val user = User("john", "John Doe") every { userRepository.getUser("john") } returns user val result = userService.getUserByUsername("john") assertEquals(user, result) verify { userRepository.getUser("john") } } }


上一篇:
下一篇:
切换中文