2

Can I run a custom rule only for a particular test method in a test class?

public class TestClassExample
{
    @Rule
    public CustomRuleForOneEqualsOne customRuleForOneEqualsOne = new CustomRuleForOneEqualsOne();

    @Test
    public void test_OneEqualsOne()
    {
        assertEquals(1, 1);
    }

    @Test
    public void test_TwoEqualsTwo()
    {
        assertEquals(2, 2);
    }
}

In the above test class can I use my customRuleForOneEqualsOne rule be used only for test method test_OneEqualsOne and not for test_TwoEqualsTwo.

I've seen other solutions on Stack Overflow:

  1. Move the two test methods into different class [say this option is not possible for particulr scenario] (or)
  2. JUnit: @Before only for some test methods? as described by this post

I can somehow use the test method name and skip over the execution of the rule but a drawback of this approach would be, each time I use the rule in a specific class for a specific set of methods, I need to add all those method names to a list to see if they are found, to determine the execution of the rest of the logic.

Is there any way to use a custom rule in a test class for a particular set of test methods while ignoring them for the other test methods in the same test class?

André Gasser
  • 1,065
  • 2
  • 14
  • 34
Gowrav
  • 289
  • 1
  • 4
  • 20

1 Answers1

1

For the best of my knowledge, @Rule applies to all tests. Therefore, if you need @Rule to be used in a single @Test method only, don't use @Rule. In that case, your code would look like this:

public class TestClassExample {

    @Test
    public void test_OneEqualsOne() {
        CustomRuleForOneEqualsOne customRuleForOneEqualsOne = new CustomRuleForOneEqualsOne();
        // use customRuleForOneEqualsOne
    }

    @Test
    public void test_TwoEqualsTwo() {
        assertEquals(2, 2);
    }

}
André Gasser
  • 1,065
  • 2
  • 14
  • 34
Boni García
  • 4,618
  • 5
  • 28
  • 44
  • I thought so, i knew it works against the concept of @Rule, but just wanted to reach out to see if it was possible – Gowrav Jan 18 '17 at 21:46