Site icon TestingDocs.com

TestNG Annotations

Overview

TestNG uses the annotations feature to build an execution framework. In this section, we will discuss some of the important TestNG annotations that are frequently used in TestNG tests.

Annotations

Annotations are Java feature that is used to add metadata to Java code. Annotations allow adding information to Java classes, methods, variables, etc. Annotations provide additional information about the code to the Java compiler. We use predefined annotations and also define custom annotations as well.

For example, sample Java Annotations:

TestNG Annotations

 

Code example

Let’s look at a sample test that uses the @Test annotation, @BeforeTest, and @AfterTest annotations. The test is an Appium mobile test.

package com.testingdocs.appium.quickstart.AppiumProject;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import io.appium.java_client.AppiumDriver;
import io.appium.java_client.remote.MobileCapabilityType;

/**
 * Sample Appium Test.
 * www.TestingDocs.com - TestNG Tutorials
 */
public class SampleTest {
	public static AppiumDriver<?> mDriver;

	@BeforeTest
	public void setup( ) throws MalformedURLException {
		DesiredCapabilities caps = new DesiredCapabilities();
		caps.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome"); 
		caps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10.0"); 
		caps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android"); 
		caps.setCapability(MobileCapabilityType.DEVICE_NAME,
 "Androidemulator"); 
		caps.setCapability("avd","Nexus_5X_API_29_x86");
		mDriver = new AppiumDriver<>
 (new URL("http://127.0.0.1:4723/wd/hub"), caps);
		mDriver.manage().timeouts().implicitlyWait(120,TimeUnit.SECONDS);  
	}

	@Test
	public static void titleTest(){
		mDriver.get("https://www.testingdocs.com/");
		Assert.assertEquals(mDriver.getTitle(),
 "Home | TestingDocs", "Check Title");
	}

	@AfterTest
	public void tearDown( ){
		mDriver.quit();
	}
}

 

The @BeforeTest sets the mobile device, browser for the test, and instantiates a mobile test driver. The test method only concentrates on the test logic of the test case. The @AfterTest kills the driver session after the test.

TestNG Tutorials on this website can be found at:

https://www.testingdocs.com/testng-framework-tutorial/

For more details on the TestNG Framework, visit the official website of TestNG at:

https://testng.org

Exit mobile version