me_digvijay
me_digvijay

Reputation: 5492

Refactoring JUnit rules from tests

I have several tests and using junit with them. In all my test files I have the junit @Rule statements. like:

public @Rule
TestWatcher resultReportingTestWatcher = new TestWatcher(this);

This and few other statements exist in all my test files. This repetion of code bothers me a little, since I think these lines can be moved to a separate place and can be used from there.

I am not very sure if this can be done, as I am very new to junit. Need giudence.

Upvotes: 1

Views: 191

Answers (1)

pobrelkey
pobrelkey

Reputation: 5973

You can put common Rules in a parent class:

public class AbstractTest {
    @Rule public SomeRule someRule = new SomeRule();
}
public class YourTest extends AbstractTest {
    @Test public void testMethod() {
        someRule.blah();
        // test some things
    }
}

Upvotes: 1

Related Questions