19

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>
Ransom Briggs
  • 3,025
  • 3
  • 32
  • 46

2 Answers2

39

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.

assylias
  • 321,522
  • 82
  • 660
  • 783
Cedric Beust
  • 15,480
  • 2
  • 55
  • 55
5

Have you tried @BeforeMethod(groups = {"current"})? I've come to the conclusion that TestNG groups and inheritance don't really work that well.

For example, the above works if you run everything in group current, but not if you run everything other than group current and the base class is used for both groups.

I'm currently refactoring all our test classes to eliminate subclassing and to make use of composition instead.

Nathan
  • 8,093
  • 8
  • 50
  • 76
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • This will work for me - since I never run the opposite of current - I just run current till everything in my feature is done - then all tests to make sure I didn't regress. – Ransom Briggs Feb 16 '11 at 18:35
  • If you have a good resource on how to use composition with TestNG - that would be really helpful as well. – Ransom Briggs Feb 16 '11 at 18:36
  • I simply wrap all my 'common' code into a class that I load in a @BeforeMethod method. i.e. simple composition rather than inheritance. – Brian Agnew Feb 16 '11 at 18:41
  • How can you compose them? I mean if I have some code in my superclass like `@AfterMethod` and `@Test` how can I compose it in my classes? – Adam Arold Mar 05 '13 at 15:08