Testing state vs. testing interaction
There are two ways a unit test can verify the behavior of production code: testing state or testing interaction.
This episode of Testing on the Toilet* does a good job of explaining the difference.
Testing state means you’re verifying that the code under test returns the right results.
Testing interactions means you’re verifying that the code under test calls certain methods properly.
The article eventually leads to conclusion that in most situations testing state is preferred.
Just because a test that uses interactions is passing doesn’t mean the code is working properly. This is why in most cases, you want to test state, not interactions.
But then goes on to examine the specific situations where it may be more useful to test interactions.
The code under test calls a method where differences in the number or order of calls would cause undesired behavior…
You’re testing a UI where the rendering details of the UI are abstracted away from the UI logic (e.g. using MVC or MVP)…
So which approach should you use when testing on Android?
In my experience writing unit tests on Android it is better to test state in your non-Android classes such as models, presenters, business logic, etc. that are decoupled from the framework.
However for classes that have dependencies on the Android framework it is preferable to test interaction in your unit tests. Your unit tests for Android classes can then be backed up by a smaller set of integration and UI tests.
This way you can rapidly verify with a greater degree of certainty your core business logic is returning the correct result but also avoid the need to go crazy mocking all the Android dependencies in your views.
* Yes this is really what the article series is called. There is also a printer-friendly version meant to be posted on the door of a bathroom stall.