catalinghita8 / android-compose-mvvm-foodies

Android sample app following best practices: Kotlin, Compose, Coroutines and Flow, Hilt, JetPack Navigation, ViewModel, MVVM, Retrofit, Coil
460 stars 87 forks source link

ViewModel unit tests #13

Open rsetkus opened 2 years ago

rsetkus commented 2 years ago

Hi,

Really like the implementation but I am struggling to find a way how to test view models. To be precise, how you would assert all values set to compose State<T> instance. Any ideas?

rsetkus commented 2 years ago

Hi @catalinghita8. Any ideas on above?

catalinghita8 commented 2 years ago

Hi @rsetkus and sorry for the late response. Asserting values of a State<*> object should be pretty straightforward. You can check out an example here.

Additional resource here.

rsetkus commented 2 years ago

Hi @catalinghita8. Thanks for the links. That was very useful.

I've read your artice and really liked it. Decided to give it a try and implement it on my own. However, it seems quite different compared to the implementation you provided above. I've applied the same workaround but it didn't work. State<*> doesn't accumulate any values.

Apparently it is known issue to Google and they expect to implement an API which would be capable to write all values written to State<*>

Warning: There are no current APIs to wait for writes to State objects in tests.

Do you have any ideas why given implementation unit tests implemented by example isn't working?

catalinghita8 commented 2 years ago

I might have to investigate why with this particular architecture has issues on asserting State<*> values. Have you tried defining some tests where the State abstraction is removed?

rsetkus commented 2 years ago

The way how I imagine testing MVI view model is to assert written values to State by given Intent. Surely, you could replace State with something else, for instance, LiveData and that might work. However, working with Compose and having only State exposed as output in the view model, is pretty neat. This is why I love your article. :thumbsup: