testng: Groups in @BeforeMethod and @AfterMethod don't work as expected

Either I’m misinterpreting or misusing TestNG-6.8.8, but it seems like the groups attribute in the @BeforeMethod and @AfterMethod aren’t working as expected.

Consider following class:

public class MyClass {
    public void method1() {
        System.out.println("Method 1 invocation");
    }
    public void method2() {
        System.out.println("Method 2 invocation");
    }
}

and following test

public class MyClassTest {
    MyClass o = new MyClass();
    @BeforeMethod(groups = "method1") 
    public void before1() {
        System.out.println("Before1");
    }
    @BeforeMethod(groups = "method2") 
    public void before2() {
        System.out.println("Before2");
    }

    @AfterMethod(groups = "method1") 
    public void after1() {
        System.out.println("After1");
    }
    @AfterMethod(groups = "method2") 
    public void after2() {
        System.out.println("After2");
    }

    @Test(groups = "method1")
    public void testMethod1() throws Exception {
        o.method1();
    }
    @Test(groups = "method2")
    public void testMethod2() throws Exception {
        o.method2();
    }
}

I would expect the output to be

Before1
Method 1 invocation
After1
Before2
Method 2 invocation
After2

However, the output is

Before1
Before2
Method 1 invocation
After1
After2
Before1
Before2
Method 2 invocation
After1
After2

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 30 (18 by maintainers)

Most upvoted comments

I tried both 6.10 and 7.0.0-beta, the test result is not expected. Here is the wiki page with details.

If groups cannot group Before and After methods, why don’t remove it to avoid confusions. I am quite confused why we need to add one more attribute onlyForGroups rather than fix groups attribute to make it workable in the expected way. (@juherr, if groups is used for test selection, why did we add it to Before/After Method annotation also?)

But anyway, onlyForGroups can work in 7.0.0-beta7.

No, @BeforeGroup doens’t do exactly what is needed here. It is only invoked once per group, whereas it would be nice to have a way to invoke a configuration method before every test from a specific group. Ditto for @AfterMethod. Right now, pretty much the only way to achieve it is the Testcase Class per Test Fixture strategy as xUnit Patterns book puts it. Sometimes it’s fine, but sometimes one ends up with too many classes this way, especially if inheritance is involved.

I propose to add a kind of group filter to @BeforeMethod. Perhaps, @BeforeMethod(onlyForGroups = ...). Then this method will only be invoked before a test method belonging to one of the listed groups. I have just tried some minimal implementation, works fine for me. Should I submit a PR to discuss it further?

And as far as I can see, issue #780 is very similar, so this should fix it too.