TestNG BeforeMethod with groups

I'm curious about using @BeforeMethod with groups. At http://testng.org/javadoc/org/testng/annotations/BeforeMethod.html it says:

alwaysRun: if set to true, this configuration method will be launched regardless of which groups it belongs to.

So, I have the following class:

 public class BeforeTest { private static final Logger LOG = Logger.getLogger(BeforeTest.class); @BeforeMethod(groups = {"g1"}, alwaysRun = false) public void setUpG1(){ sleep(); LOG.info("BeforeMethod G1"); } @Test(groups = {"g1"}) public void g1Test(){ sleep(); LOG.info("g1Test()"); } @BeforeMethod(groups = {"g2"}, alwaysRun = false) public void setUpG2(){ sleep(); LOG.info("BeforeMethod G2"); } @Test(groups = {"g2"}) public void g2Test(){ sleep(); LOG.info("g2Test()"); } private void sleep(){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } } 

What outputs:

 BeforeMethod G1 BeforeMethod G2 g1Test() BeforeMethod G1 BeforeMethod G2 g2Test() 

Besides the fact that, in my opinion, awaysRun is false by default, can someone explain to me why both methods are called without considering groups before each test? Something like @Test (skipBeforeMethod = "setUpG1") will work too.

I am using IntelliJ IDEA CE 10.5.2. I ran it using gradle 1.0-milestone-3.

+8
java testng
source share
2 answers

How do you call TestNG? Do you use any groups?

If you run it, both @BeforeMethods methods will be launched. If you run "g1", only setupG1 will start, etc.

+2
source share

I would recommend not using alwaysRun = true, but creating a special group for config methods (we use "config") and annotating everything before * () and after * () methods with groups = "config".

All testing methods can be annotated with any group that you like, for example. "foo" and "bar".

Then in your run you do:

 -Dgroups=config,foo 

or

 -Dgroups=config,bar 

If you add another group "newGroup", you do not need to go through all the configuration methods and add "newGroup" to them, you just run:

 -Dgroups=config,newGroup 

This simplifies group management.

If you (by mistake?) Run something like:

 -Dgroups=config,nonExistingGroup 

No tests (and no configuration methods) will be executed, since you actually do not have any tests annotated for the "nonExistingGroup", and the configuration methods are only executed if there are "corresponding tests" that require these configuration methods.

0
source share

All Articles