Sobes.tech
Junior

What tools and libraries for unit testing are used in Kotlin?

sobes.tech AI

Answer from AI

JUnit 5. A cross-platform framework for unit testing, a standard for JVM.

Mockito/MockK. Libraries for creating mocks and stubs of objects, simplifying the isolation of testable code. MockK is idiomatic for Kotlin.

AssertJ/Truth. Libraries for writing flexible and readable assertions.

Kotest. A multifunctional testing framework written in Kotlin, supporting various styles of writing tests.

Spek 2. A specification-style unit testing framework based on Kotlin.

Kotlinx.coroutines.test. A library for testing code with coroutines.

// Example of using JUnit 5 + MockK + AssertJ
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
import org.assertj.core.api.Assertions.assertThat

class MyServiceTest {

    private val repository: MyRepository = mock() // Mocking dependency
    private val service = MyService(repository)

    @Test
    fun `getData should return data from repository`() {
        val expectedData = "some data"
        // Mockito.whenever(repository.fetchData()).thenReturn(expectedData) // Example with Mockito
        // every { repository.fetchData() } returns expectedData // Example with MockK

        val actualData = service.getData()

        assertThat(actualData).isEqualTo(expectedData) // Assertion with AssertJ
        // verify { repository.fetchData() } // Example verification with MockK
    }
}

interface MyRepository {
    fun fetchData(): String
}

class MyService(private val repository: MyRepository) {
    fun getData(): String {
        return repository.fetchData()
    }
}
What tools and libraries for unit testing are used in… - sobes.tech