Maven Project Configurasion
Integrating TestNG into a Java project managed by Maven requires adding the apppropriate dependency to the pom.xml file. This allows for automated dependency management and lifecycle integration within IntelliJ IDEA.
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.7.0</version>
<scope>test</scope>
</dependency>
The <scope> element is crucial for defining dependency availability. If set to test, TestNG is only available in the src/test/java directory. If you encounter compilation errors while using @Test annotations, verify that your code is in the correct directory or adjust the scope:
- compile: The default scope; used for all phases and bundled with the final artifact.
- provided: Similar to compile, but expects the JDK or container to provide the dependency at runtime.
- runtime: Required for execution but not for compilation, such as database drivers.
- test: Available only during test compilation and execution; not included in the application package.
- system: Requires a manual path to a local JAR file; generally discouraged.
Annotation Hierarchy and Execution Order
TestNG operates on a clear hierarchy of execution levels: Suite, Test, Class, and Method. Annotations allow developers to hook into specific points of the testing lifecycle to manage setup and teardown tasks efficiently.
import org.testng.annotations.*;
public class SystemLifecycleTest {
@BeforeSuite
public void initializeGlobalSettings() {
System.out.println("Status: Global suite setup initiated.");
}
@AfterSuite
public void finalizeGlobalSettings() {
System.out.println("Status: Global suite teardown completed.");
}
@BeforeClass
public void setupClassEnvironment() {
System.out.println("Status: Preparing environment for the current test class.");
}
@AfterClass
public void teardownClassEnvironment() {
System.out.println("Status: Cleaning up the environment for the test class.");
}
@BeforeTest
public void configureModuleResources() {
System.out.println("Status: Allocating resources for the <test> block.");
}
@AfterTest
public void releaseModuleResources() {
System.out.println("Status: Deallocating resources for the <test> block.");
}
@BeforeMethod
public void prepTestExecution() {
System.out.println("Status: Running pre-test method logic.");
}
@AfterMethod
public void cleanupTestExecution() {
System.out.println("Status: Running post-test method logic.");
}
@Test
public void validateCoreFunctionality() {
System.out.println("Action: Executing core functionality validation.");
}
@Test
public void validateEdgeCaseScenarios() {
System.out.println("Action: Executing edge case scenario validation.");
}
}
In this structure, @BeforeSuite and @AfterSuite run once per execution of a suite definition. @BeforeTest and @AfterTest apply to the test sections defined in a testng.xml file. @BeforeClass and @AfterClass run once per class, while @BeforeMethod and @AfterMethod wrap around every individual method annotated with @Test.