How to write a JUnit rule ?


If you are using both Coroutines and ViewModel in your code, it is preety highly likely that you can probably also be using ViewModel scope. So instead of writing that same @Before and @After the code that we write to setup and tear down the Coroutine Dispatcher  for every single ViewModel test we do. We can use custom JUnit rule to avoid that bolierplate of codes.

JUnit Rule
They are classses where you define generic testing code that can execute before, after or even during a test. It's basically a way to take that code that would have been in the app before and after method and instead put it into a class where it can easily be re-used.


Here we will write a JUnit test Rule to swap the dispatcher.

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.rules.TestWatcher
import org.junit.runner.Description

@ExperimentalCoroutinesApiclass MainCoroutineRule(val dispatcher: TestCoroutineDispatcher = TestCoroutineDispatcher()):
    TestWatcher(),    TestCoroutineScope by TestCoroutineScope(dispatcher) 
{
    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
        cleanupTestCoroutines()
        Dispatchers.resetMain()
    }
}


TestWatcher() extends TestRule Interface and it is what makes our Coroutine rule a JUnit rule.


Using it in your ViewModelTest

// we use the custom maincoroutinerule instead of each setup and tear down@get:Rulevar mainCoroutineRule = MainCoroutineRule()




Comments

Popular Posts