https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

stojan

01/20/2023, 10:23 AM
I have this code:
Copy code
val testContext: Context = ApplicationProvider.getApplicationContext()
    val testCoroutineDispatcher = StandardTestDispatcher()
    val testCoroutineScope = TestScope(testCoroutineDispatcher + Job())

    val testDataStore: DataStore<Preferences> = PreferenceDataStoreFactory.create(
        scope = testCoroutineScope,
        produceFile = { testContext.preferencesDataStoreFile("test_datastore") }
    )
in my tests I use
testCoroutineScope.runTest {}
what is the proper way to run a suspend function (to do some clean up) after every test using
@After
? things I tried and didn't work:
testCoroutineScope.runTest {}
runBlocking {}
runBlocking(testCoroutineDispatcher) {}
s

Sam

01/20/2023, 10:35 AM
If you want to run code before the test scope is cleaned up, it’s not really possible to do it in the
@After
method. One way to do it is with a wrapper function:
Copy code
fun TestScope.runTestAndCleanup(body: TestScope.() -> Unit) = runTest {
    try {
        body()
    } finally {
        cleanup()
    }
}
10 Views