How to use Interface ITestResult class of org.testng package

Best Testng code snippet using org.testng.Interface ITestResult

Run Testng automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1package org.testng.internal;
2
3import java.util.List;
4import java.util.Set;
5
6import org.testng.IConfigurationListener;
7import org.testng.ITestListener;
8import org.testng.ITestNGMethod;
9import org.testng.ITestResult;
10import org.testng.xml.XmlTest;
11
12/**
13 * An interface defining the notification for @Test results and also
14 * \@Configuration results.
15 *
16 * @author <a href="mailto:cedric@beust.com">Cedric Beust</a>
17 * @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>
18 */
19public interface ITestResultNotifier {
20
21  Set<ITestResult> getPassedTests(ITestNGMethod tm);
22
23  Set<ITestResult> getFailedTests(ITestNGMethod tm);
24
25  Set<ITestResult> getSkippedTests(ITestNGMethod tm);
26
27  void addPassedTest(ITestNGMethod tm, ITestResult tr);
28
29  void addSkippedTest(ITestNGMethod tm, ITestResult tr);
30
31  void addFailedTest(ITestNGMethod tm, ITestResult tr);
32
33  void addFailedButWithinSuccessPercentageTest(ITestNGMethod tm, ITestResult tr);
34
35  void addInvokedMethod(InvokedMethod im);
36
37  XmlTest getTest();
38
39  List<ITestListener> getTestListeners();
40
41  List<IConfigurationListener> getConfigurationListeners();
42}
43
Full Screen
copy
1package main.java.com.dbyl.appiumCore.testng;
2
3import java.lang.reflect.Method;
4import java.util.List;
5
6import org.testng.ITestContext;
7import org.testng.ITestNGMethod;
8import org.testng.ITestResult;
9import org.testng.TestListenerAdapter;
10
11import main.java.com.dbyl.appiumCore.utils.CaseId;
12
13/**
14 * The listener interface for receiving testng events. The class that is
15 * interested in processing a testng event implements this interface, and the
16 * object created with that class is registered with a component using the
17 * component's <code>addTestngListener<code> method. When the testng event
18 * occurs, that object's appropriate method is invoked.
19 *
20 * @author Young
21 * @version V1.0
22 * @see TestngEvent
23 */
24public class TestngListener extends TestListenerAdapter {
25
26	/*
27	 * (non-Javadoc)
28	 * 
29	 * @see org.testng.TestListenerAdapter#onTestFailure(org.testng.ITestResult)
30	 */
31	@Override
32	public void onTestFailure(ITestResult tr) {
33		ITestNGMethod im = tr.getMethod();
34		getCaseID(im);
35		super.onTestFailure(tr);
36	}
37
38	/*
39	 * (non-Javadoc)
40	 * 
41	 * @see org.testng.TestListenerAdapter#onTestSkipped(org.testng.ITestResult)
42	 */
43	@Override
44	public void onTestSkipped(ITestResult tr) {
45		ITestNGMethod im = tr.getMethod();
46		getCaseID(im);
47		super.onTestSkipped(tr);
48	}
49
50	/*
51	 * (non-Javadoc)
52	 * 
53	 * @see org.testng.TestListenerAdapter#onStart(org.testng.ITestContext)
54	 */
55	@Override
56	public void onStart(ITestContext testContext) {
57		System.out.println("Start Test");
58		super.onStart(testContext);
59	}
60
61	/*
62	 * (non-Javadoc)
63	 * 
64	 * @see org.testng.TestListenerAdapter#onFinish(org.testng.ITestContext)
65	 */
66	@Override
67	public void onFinish(ITestContext testContext) {
68		// TODO Auto-generated method stub
69		super.onFinish(testContext);
70	}
71
72	/*
73	 * (non-Javadoc)
74	 * 
75	 * @see org.testng.TestListenerAdapter#getFailedTests()
76	 */
77	@Override
78	public List<ITestResult> getFailedTests() {
79		// TODO Auto-generated method stub
80		return super.getFailedTests();
81	}
82
83	/*
84	 * (non-Javadoc)
85	 * 
86	 * @see org.testng.TestListenerAdapter#getPassedTests()
87	 */
88	@Override
89	public List<ITestResult> getPassedTests() {
90		// TODO Auto-generated method stub
91		return super.getPassedTests();
92	}
93
94	/*
95	 * (non-Javadoc)
96	 * 
97	 * @see org.testng.TestListenerAdapter#getSkippedTests()
98	 */
99	@Override
100	public List<ITestResult> getSkippedTests() {
101		// TODO Auto-generated method stub
102		return super.getSkippedTests();
103	}
104
105	/*
106	 * (non-Javadoc)
107	 * 
108	 * @see org.testng.TestListenerAdapter#onTestStart(org.testng.ITestResult)
109	 */
110	@Override
111	public void onTestStart(ITestResult result) {
112		ITestNGMethod im = result.getMethod();
113		getCaseID(im);
114		super.onTestStart(result);
115	}
116
117	/**
118	 * Gets the case ID.
119	 *
120	 * @param im
121	 *            the im
122	 * @return the case ID
123	 */
124	private String[] getCaseID(ITestNGMethod im) {
125		Method m = im.getConstructorOrMethod().getMethod();
126		CaseId caseId = m.getAnnotation(CaseId.class);
127		if (null != caseId) {
128			for (String str : caseId.id()) {
129				System.out.println("++++++++++++++++>>>>>>>>>>>>>\n\n\n" + str + "<<<<<<<\n\n");
130			}
131			return caseId.id();
132		}
133		return null;
134	}
135
136	/*
137	 * (non-Javadoc)
138	 * 
139	 * @see org.testng.TestListenerAdapter#getTestContexts()
140	 */
141	@Override
142	public List<ITestContext> getTestContexts() {
143		// TODO Auto-generated method stub
144		return super.getTestContexts();
145	}
146
147}
148
Full Screen
copy
1    // Pages Object Initialization
2    loginPages = PageFactory.initElements(driver, LoginPages.class);
3    logoutPages = PageFactory.initElements(driver, LogoutPages.class);
4    adminPages = PageFactory.initElements(driver, AdminPages.class);
5
Full Screen
copy
1ExtentTest extentTest = ExtentTestManager.startTest(method.getName(), "");
2
Full Screen
copy
1       public synchronized void afterInvocation(IInvokedMethod method, ITestResult testResult){
2        if (method.isTestMethod() && testResult.getStatus()==2) {
3
4                File scrFile = (dataMethod.getAndroidDriver()).getScreenshotAs(OutputType.FILE);
5                String dest = System.getProperty("user.dir") + "/resources/screenshots/" + dataMethod.getDriver().getSessionId() + ".png";
6
7                File destination = new File(dest);
8                try {
9                    FileUtils.copyFile(scrFile, destination);
10                    dataMethod.setScreenshotPath(destination.getAbsolutePath());
11                } catch (IOException e) {
12                    e.printStackTrace();
13                }
14                System.err.println("Path:" + dataMethod.getScreenshotPath());
15
16        }
17
Full Screen
copy
1public static ITestContext setContext(ITestContext iTestContext, WebDriver driver) {
2        iTestContext.setAttribute("driver", driver);
3
4        return iTestContext;
5    }
6
Full Screen
copy
1public class ChromeTestManager {
2
3        private WebDriverManager webDriverManager = new WebDriverManager();
4        private WebDriver driver;
5
6        private LoginPages loginPages;
7        private AdminPages adminPages;
8
9        private static ITestContext context;  // creating a ITestContext variable
10
11        @BeforeClass
12        //@Parameters({"browser"})
13        public void setupTest(ITestContext iTestContext) throws MalformedURLException {
14            System.out.println("BeforeMethod is started. " + Thread.currentThread().getId());
15            // Set & Get ThreadLocal Driver with Browser
16
17            webDriverManager.createDriver("chrome");
18            driver = webDriverManager.getDriver(); 
19
20            this.context = setContext(iTestContext, driver);  // setting the driver into context
21
22            // Pages Object Initialization
23            loginPages = PageFactory.initElements(driver, LoginPages.class);
24            logoutPages = PageFactory.initElements(driver, LogoutPages.class);
25            adminPages = PageFactory.initElements(driver, AdminPages.class);
26        }
27
Full Screen
copy
1@Override
2    public synchronized void onTestFailure(ITestResult result) {
3        WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver");  // here we are accessing the driver object that we added in Test class  
4
5}
6
Full Screen
copy
1@Override
2    public synchronized void onTestFailure(ITestResult result) {
3        System.out.println("!!!!!!!!!!!!!!!!!!!! Test Failed !!!!!!!!!!!!!!!!!!!!");
4
5        WebDriver driver = (WebDriver) result.getTestContext().getAttribute("driver"); // accessing driver here
6        String feature = getClass().getName();
7        String screenShot;
8        try {
9            screenShot = CaptureScreenshot.captureScreen(driver, CaptureScreenshot.generateFileName(feature));
10            test.addScreenCaptureFromPath(screenShotPath);  // I am assuming that the "screenShot" is fully qualified path with extension e.g "C:\Users\12345\Desktop\sfgfdh.PNG"
11        } catch (IOException ex) {    
12            LogManager.logger.log(Level.INFO, "Exception: " + ex.getMessage());
13        }
14
15    }
16
Full Screen
copy
1import java.lang.annotation.Retention;
2import java.lang.annotation.Target;
3
4import static java.lang.annotation.ElementType.METHOD;
5
6@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
7@Target(METHOD)
8public @interface SessionId {
9    String id();
10}
11
Full Screen
copy
1import org.testng.ITestResult;
2import org.testng.annotations.AfterMethod;
3import org.testng.annotations.BeforeMethod;
4
5import java.lang.reflect.Method;
6
7public class BaseRun {
8    private String getSession(Method method) {
9        SessionId id = method.getAnnotation(SessionId.class);
10        if (id == null) {
11            return "";
12        }
13        return id.id();
14    }
15
16    @BeforeMethod
17    public void beforeMethod(Method method, ITestResult result) {
18        String id = getSession(method);
19        result.setAttribute("session", id);
20    }
21
22    @AfterMethod
23    public void afterMethod(ITestResult result) {
24        System.out.println("Session Id = " + result.getAttribute("session"));
25    }
26
27}
28
Full Screen
copy
1import org.testng.annotations.Test;
2
3public class Run1 extends BaseRun {
4    @Test
5    @SessionId(id = "Testing Runner 1")
6    public void testMethod() {
7        System.out.println("This is a test case");
8    }
9}
10
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)