Android Tests
Here we will introduce some tips for testing Android applications.
To understand the basics of testing, please refer to the Test documentation first.
Unit Tests
If the subject to be tested does not require the Android Framework, you can start testing by mocking the application class using mock libraries such as mockito or MockK.
When calling Koject.startTest()
, specify the mocked application class as follows:
class SampleViewModelTest() {
@Before
fun start() {
Koject.startTest {
application(mock(Application::class.java))
}
}
@After
fun stop() {
Koject.stop()
}
@Test
fun test() {
val viewModel = inject<SampleViewModel>()
/* ... */
}
}
Create JUnit rule if you need it.
class KojectTestRule : TestWatcher() {
override fun starting(description: Description) {
Koject.startTest {
application(mock(Application::class.java))
}
}
override fun finished(description: Description) {
Koject.stop()
}
}
class SampleViewModelTest() {
@get:Rule
val kojectTestRule = KojectTestRule()
@Test
fun test() {
val viewModel = inject<SampleViewModel>()
/* ... */
}
}
Instrumented Tests / Robolectric Tests
To run instrumented tests on a physical device or emulator, or run unit tests using Robolectric, you need to replace the Koject.start()
call in your application class with Koject.startTest()
.
First, create a test application class using Koject.startTest()
.
class TestApplication : Application() {
override fun onCreate() {
super.onCreate()
Koject.startTest {
application(this@TestApplication)
}
}
}
Next, create a custom runner to use the test application class.
class TestRunner : AndroidJUnitRunner() {
override fun newApplication(
classLoader: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(classLoader, TestApplication::class.java.name, context)
}
}
Don't forget to register the runner in the build.gradle.kts
file.
android {
defaultConfig {
/* ... */
+ testInstrumentationRunner = "com.mypackage.test.TestRunner"
}
/* ... */
}
After that, you can write tests as usual.
@RunWith(AndroidJUnit4::class)
class SampleActivityTest() {
@Test
fun test() {
val scenario = launchActivity<SampleActivit>()
}
}
Configuring KojectExtras
If you are using KojectExtras and need more detailed settings, consider starting Koject for each test instead of in the Application
.
class TestApplication : Application() {
override fun onCreate() {
super.onCreate()
// Do not start Koject
}
}
@RunWith(AndroidJUnit4::class)
class SampleActivityTest() {
@Before
fun start() {
Koject.startTest {
application(ApplicationProvider.getApplicationContext())
addExtras(/* ... */)
}
}
@After
fun stop() {
Koject.stop()
}
@Test
fun test() {
val scenario = launchActivity<SampleActivit>()
}
}