Putting aside the long lasting debate right now about whether you should use RxJava or coroutines for your asynchronous code on Android, both camps often hit the same problem. How do I write unit tests for this?

Unit testing asynchronous code is tricky, because we may need to know how to properly test callback APIs, or perhaps we just want things to run instantly and not worry about thread changes. We may also be wondering how to handle not having a “main” thread in a junit test, unlike a connected test. This post will be focusing on handling that last one.

A number of developers preach a single activity architecture on Android, which is something I’ve been trying to move forward to as well. In the process, though, I ran into one tricky problem. I don’t have something like startActivityResult for fragments. If you’re unfamiliar, startActivityForResult is a method that allows you to launch an activity with a specific request code, and when that activity finishes, your first activity will get a callback in onActivityResult and can do stuff with it.

This post is going to walk through how we can achieve that same affect using fragments.

So far we’ve covered four big buzzwords used in our application:

  1. Model-View-ViewModel
  2. Room
  3. RxJava
  4. Repository Pattern

Now, we should circle back to the beginning. Following our diagram outlined in the previous parts, the next component we can begin to work on is our AccountViewModel:

Android Essence

Naturally, this may bring up some confusion. We already discussed ViewModels in part 1. Well, depending on context, we may not be referring to the same thing.