Search code examples
unit-testingjunitjunit4junit-rule

Apply a JUnit Custom @Rule a particular test method


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?


Solution

  • 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);
        }
    
    }