TestRule are the only way (outside of the @Parameters concept) to provides test fixtures, action before and after tests, etc. Only one TestRule chain is allowed for a test class. If a test class extends another one, one chain is allowed for each test class and they will be chained from the upper class to the lower one.
Conceptually, a test rule, at execution time, will receive a test statement as parameter and compute another test statement.
TestRule. Once you have the outer test rule, it is possible to chain them by using the {@link #around(TestRule)} or{@link #around(Supplier)} methods. One single TestRule (which can be used asa start of the chain, or later), can be builded by : before method that will produce a rule to be executed before a test ; The after method will do the same, but with a code to be executed after a test. import org.mockito.Mock; import org.mockito.Mockito; import ch.powerunit.Rule; import ch.powerunit.Test; import ch.powerunit.TestRule; import ch.powerunit.TestSuite; public class MockitoRuleTest implements TestSuite { public interface Mockable { void run(); } @Mock private Mockable mock; @Rule public final TestRule testRule = mockitoRule() .around(before(this::prepare)); public void prepare() { Mockito.doThrow(new RuntimeException("test")).when(mock).run(); } @Test public void testException() { assertWhen((p) -> mock.run()).throwException( isA(RuntimeException.class)); } } In this case, the defined chain, will first apply the rule provided by mockitoRule, and then apply the rule included inside the around. The before method usage inside the around will ensure the method prepare is executed before each test. The sequence of execution, will be :
prepare.testException. | |
| |