Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple TestRules in the same test

I have written a custom TestRule to use with my Android test suite. It populates a table in the database used by the app under test. Now I need to use this DataRule along with ActivityTestRule. Can I have two fields of my test class annotated with @Rule? How do I control the order in which the rules are applied?

Background:

The Android API provides a TestRule for starting an Activity which is the core class for every app with a UI. My app has a database and I have several tests which require the database to be pre-populated with some known data. Previously, with JUnit3-based tests, I used an abstract superclass to centralize the code which prepares the database and then I extended this superclass for different test cases. Now I am trying to implement the same logic using JUnit 4. I learned recently that test rules are one way to provide logic which is reused across tests, so I am trying to move the logic from my superclass to a test rule. Is this an appropriate way to achieve my goal?

like image 839
Code-Apprentice Avatar asked Feb 12 '16 22:02

Code-Apprentice


2 Answers

You certainly can have multiple @Rule fields in a single test. I'm not sure what the default ordering of rule application is, or if it's even well-defined. However, if ordering is important you can control it with a RuleChain which allows you to define an order on how rules are applied when you have multiple rules in a test case.

From the Javadoc...

@Rule
public RuleChain chain = RuleChain
                           .outerRule(new LoggingRule("outer rule")
                           .around(new LoggingRule("middle rule")
                           .around(new LoggingRule("inner rule");
like image 122
sisyphus Avatar answered Sep 24 '22 20:09

sisyphus


RuleChain is deprecated and since 4.13 you can make use of order parameter in Rule.

org.junit.Rule annotation has a parameter "order" which you can use to order the Rules in one file.

check the doc in the link below

Rule.java

like image 38
Bisma Frühling Avatar answered Sep 25 '22 20:09

Bisma Frühling