简体   繁体   中英

ViewModel + Room test coverage in UnitTest

I have an unit test like this:

       ... 
        subj.mintToken(to, value, uri)
        advanceUntilIdle()
        ...
        val pendingTxFinalState = subj.uiState.value.pendingTx.count()
        assertThat("Model should have a single pending tx, but has $pendingTxFinalState", pendingTxFinalState == 1)
        ...

The model field in ViewModel is populated by the request to cache in the init {} block. Each change in table would trigger this coroutine flow. This piece of unit test checks correctness of this functionality. The current issue is this Flow in init {} block is triggered only on the test start when ViewModel instance is created. It does not respond on update in table.

It is important to note I don't use in test a room database neither test database, but FakeCacheRepository where behaviour of methods are emulated by flow with mocked data. However the behaviour of flow should be the same as there is still in change in underlying data.

    val txPool = ConcurrentLinkedQueue<ITransaction>()

    override fun createChainTx(tx: ITransaction): Flow<ITransaction> {
        return flow {
            txPool.add(tx)
            emit(tx)
        }
    }

    override fun getAllChainTransactions(): Flow<List<ITransaction>> {
        return flow {
            emit(txPool.toList())
        }
    }

Do you see the issue here or better way to test this?

My guess is you're writing you're own FakeCacheRepo and in the update function you are calling createChainTx. The value of the flow isn't updating though because the create function doesn't just update the value it creates a new flow instead of updating the old one. You can modify the set up to emit continuously in a loop (with some buffer delay) based on a variable. Then when you change the variable it will change what the current flow is emiting as expected.

The code example here is roughly doing that: https://developer.android.com/kotlin/flow#create

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM