TestNG @BeforeMethod method not called when it resides in superclass and a specific group is run

Ransom Briggs picture Ransom Briggs · Feb 16, 2011 · Viewed 18.4k times · Source

I am trying to use a group to run a subset of tests relevant to what I am working on called "current". The problem is that if I use a superclass to do some setup in a @BeforeMethod, the method runs when I run all tests, but does not when I run with just the group "current" specified.

So when I run all tests, the emptyTest fails because the @BeforeMethod is called, when just running group current, the method is not called. Note: If I add @Test(groups = {"current"}) to the subclass, then it does run - however, it runs all subclasses not labelled with "current" as well, which defeats the purpose of the "current" group.

If there is a better way to accomplish this behavior, I am open to all solutions.

Thanks, Ransom

Superclass:

public class TestNGSuperclass {
    @BeforeMethod
    public void failingToShowThatItIsNotRun() {
        Assert.fail();
    }
}

Subclass:

@Test(groups = {"current"})
public class TestNGCurrentGroup extends TestNGSuperclass {
    public void emptyTest() {}
}

TestNG Configuration:

<test name="current">
    <groups>
        <run>
            <include name="current"/>
        </run>
    </groups>
    <packages>
        <package name="uiowa.wf.test.*"/>
    </packages>
</test>
<test name="all-tests">
    <packages>
       <package name="uiowa.wf.test.*"/>
    </packages>
</test>

Answer

Cedric Beust picture Cedric Beust · Feb 16, 2011

Your @BeforeMethod needs to be part of the group you are running.

You can also use @BeforeMethod(alwaysRun = true) if you don't want to hardcode the value of your group and if you think you will always want to run this method, regardless of the group you are currently running.