Testing
Software testing is the process of evaluating a software application to uncover errors, defects, or unexpected behavior. It involves executing the application under controlled conditions and verifying its output against expected results. Testing plays a crucial role in ensuring the quality, reliability, and functionality of software.
Usage
Dependencies
Within your app
module’s build.gradle.kts
file, incorporate the following dependencies:
implementation(project(":testing"))
Explanation
InstantExecutorExtension
This extension ensures all tasks submitted to Dispatchers (like IO or Main) are executed immediately on the main thread during tests. This eliminates the need for idling resources or waiting for asynchronous tasks to complete.
MainDispatcherExtension
This extension allows you to control the dispatcher used for the Dispatchers.Main coroutine context within your tests. By default, it utilizes UnconfinedTestDispatcher for efficient test execution.
Example
@ExtendWith(value = [InstantExecutorExtension::class, MainDispatcherExtension::class])
internal class MyTestClass {
@Test
fun `some async test`() = runTest {
val expectedState = // Some expected state
// Turbine to handle Flow
viewModel.uiState.test {
val state = awaitItem()
Assertions.assertEquals(expectedState, state)
}
}
@Test
fun `test some action`() = runTest {
viewModel.onAction(SomeAction)
coVerify(exactly = 1) { someUseCase.execute(any()) }
viewModel.useActionState.test {
val state = awaitItem()
Assertions.assertTrue(state is Success)
}
}
}
The runTest
function is a test coroutine builder that launches a new coroutine for each test. It configures the test dispatcher to use the UnconfinedTestDispatcher for efficient execution.
More information on MockK can be found in the official documentation .
More information on Turbine can be found in the official documentation .
More information on Kotlinx Coroutines Test can be found in the official documentation .