Creating A (Basic) Custom Rule For Testing
Have you realized that in some situations the basic ActivityRule is not enough to cover all the scenario for your tests? Moreover, what if we can write custom rules that define custom behaviors to save us from writing tons of code and to make like sort of setup procedures more shippable to other classes?
The Scenario
Let’s imagine this particular scenario: we have a UI test class in which idling resources were registered/unregistered within @Before / @After methods. (Let me share a basic but not less powerful sample using Idling Resources)
What if we get rid of them and create a util test rule for this idle resources? This, because what happens when we have 20–30 test classes that need to work with idling resources?, we need to replicate this code within every one of them and this is not cool.
Let’s take a look at this simple example:
So, we can simplify this creating our own EspressoIdleResourcesTestRule as follows:
This example shows the use of TestWatcher, that already implements TestRule and does all the work for us, on a simpler and more clear way. The things to higlight here is that implementing TestWatcher lead us to override several methods, but in our case we only override starting and finished, simulating the @Before and @After methods.
Updating The Test
Now, we can add this new rule to the previous test and the others that need idling resources and then the behavior will be the same and less code was written.
This is then one of the several ways we can write custom test rules in order to have clearer and nicer code.
That’s all for today and don’t forget to take a look at my profile to read more examples about testing an other Android stuff.