How to clean up data store after each test in unit...
# android
a
How to clean up data store after each test in unit tests? Using
Copy code
@After
    fun tearDown() = testScope.runTest {
        testDataStore.edit {
            it.clear()
        }
        testScope.cancel()
    }
Getting error
Only a single call to
runTest
can be performed during one test.
As both the
test
method and
tearDown()
uses
runTest
Stackoverflow question - https://stackoverflow.com/questions/77025162/data-store-clean-up-in-unit-test-error-only-a-single-call-to-runtest-can-be Please help. Thanks
s
initialize the test scope per-test
p
I think using
runBlocking()
is a valid use case for this. From documentation:
It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
And I think this is probably a valid case, where you need to bridge regular blocking code. JUnit doesn't support suspending. Alternatively, you could probably also make a helper function, that does cleanup.
Copy code
@Test
fun someTest() {
    runTestAndCleanup {
        // test code
    }
}

private fun runTestAndCleanup(block: suspend () -> Unit) = runTest {
    try {
        block()
    } catch(e) {
        TODO("cleanup")
        throw e
    }
}
a
Thanks, the helper function seems like a better idea. Currently I had the cleanup code in a separate method and I was calling it in all tests. (it can be missed easily in new tests.)
235 Views