TestNG @BeforeGroups Annotations (original) (raw)

Last Updated : 6 Aug, 2025

@BeforeGroups is one of the TestNG Annotations. When you annotate a method with @BeforeGroups, TestNG ensures that this method is invoked before any test method belonging to the specified groups is executed. This annotation allows developers to specify various actions to be taken before all the methods of the current group within a class finish their execution.

Let's understand the @BeforeGroups annotation through an example.

**Step 1: In a Maven Project, create a TestNG Class that contains @BeforeGroups.

**Before_Group.Java

Java `

package com.geeksforgeeks.test;

import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test;

public class Before_Group {

@BeforeGroups(groups = {"authentication"})
public void setUpAuthentication() {
    System.out.println("Database setup complete for authentication tests.");
}

@Test(groups = {"authentication"})
public void testLogin() {
    System.out.println("Login test executed.");
}
@Test(groups = {"authentication"})
public void testSignup() {
    System.out.println("Signup test executed.");
}
@Test(groups = {"authentication"})
public void testSignout() {
    System.out.println("Signout test executed.");
}

}

`

**Now, let's explain what this code does:

**Package Declaration: The code is in the com.geeksforgeeks.test package.

**Imports: The code imports annotations from the TestNG framework (org.testng.annotations.BeforeGroups and org.testng.annotations.Test).

**Before_Group Class: This is the main test class.

**setUpAuthentication Method (@BeforeGroups(groups = {"authentication"})):

**Test Methods (@Test(groups = {"authentication"})):

**Step 2: Now, we create the AnnotationsTest.xml file to configure the Before_Groups.Java.

XML `

`

**Step 3: Run the AnnotationsTest.xml. Right click on the AnnotationsTest.xml file, move the cursor down to Run As and then click on the TestNG Suite.

Output of BeforeGroups Annotations

Output of BeforeGroups Annotations