Source:How do I efficiently iterate over each entry in a Java Map?
package com.test;
public class Main {
public static void main(String[] args) {
System.out.println("salam 2nya\n");
}
}
Best Testng code snippet using org.testng.Interface I
Source:TestListenerFailPass.java
1package com.quiksilver.util;2import java.io.File;3import java.io.IOException;4import java.text.DateFormat;5import java.text.SimpleDateFormat;6import java.util.Date;7import org.apache.commons.io.FileUtils;8import org.openqa.selenium.OutputType;9import org.openqa.selenium.TakesScreenshot;10import org.openqa.selenium.WebDriver;11import org.testng.ISuite;12import org.testng.ITestResult;13import org.testng.Reporter;14import org.testng.TestListenerAdapter;15import org.testng.annotations.AfterMethod;16import org.testng.annotations.Listeners;17import org.apache.log4j.*;18/*19 * It's very easy to generate your own reports with TestNG with Listeners and Reporters:20Listeners implement the interface org.testng.ITestListener and are notified in real time 21of when a test starts, passes, fails, etc...22Reporters implement the interface org.testng.IReporter and are notified when all the suites 23have been run by TestNG. The IReporter instance receives a list of objects24 that describe the entire test run.25 */26/*27 * I chose to extend TestListenerAdapter, which implements ITestListener with empty methods, 28 * so I don't have to override other methods from the interface that I have no interest in. 29 * If you try public class 'TestScreenshotOnFailure implements ITestResult' - implementing an interface instead of 30 * extending your class with a TestNG class that implements the interface you want (ITestResult) then31 * you will have to override ALL (15-18) methods declared in ITestResult interface which is not productive32 */33/*THIS CLASS DEFINES RULES for DEFAULT BEHAVIOUR of org.testng.ITestResult.Failure or Success34 * http://testng.org/javadocs/constant-values.html#org.testng.ITestResult.FAILURE35 * TO USE THIS CLASS:36 * 37 *put this annotation before you class where you define your test methods38 * @Listeners({ com.quicksilver.util.TestListenerFailPass.class })39 */40public class TestListenerFailPass extends TestListenerAdapter {41 42 WebDriver driver;43 private int m_count = 0;44 Logger log=WebDriverManager.LoggerGetInstance();45 46 ReadingProperties rp = new ReadingProperties();47 String failPath=rp.readConfigProperties("fail.screenshot.path");48 String passPath=rp.readConfigProperties("pass.screenshot.path");49 String usergenPath =rp.readConfigProperties("usergen.screenshot.path");50 51 @Override52 public void onTestFailure(ITestResult tr) {53 //log("Failed");//testng logger54 driver = WebDriverManager.getDriverInstance();55 WebDriverManager.getBrowser(driver);56 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);57 DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");58 String destDir = System.getProperty("user.dir")+failPath;59 new File(destDir).mkdirs();60 String destFile = dateFormat.format(new Date()) + ".png";61 try {62 FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));63 } catch (IOException e) {64 e.printStackTrace();65 System.out.println("Could not take screenshot on failure"+ tr.getInstanceName());//getInstanceName =package+className66 log.debug("Could not take screenshot on failure"+ tr.getInstanceName());//getInstanceName =package+className67 }68 Reporter.setEscapeHtml(false);69 Reporter.log("Saved <a href=../screenshot/FAIL/" + destFile + ">Screenshot</a>");70 }71 @Override72 public void onTestSkipped(ITestResult tr) {73 log("Skipped test");74 Reporter.log("Skipped test to avoid test failure due to dependency");75 }76 @Override77 public void onTestSuccess(ITestResult tr) {78 //log("Pass");79 driver = WebDriverManager.getDriverInstance();80 File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);81 DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy__hh_mm_ssaa");82 String destDir = System.getProperty("user.dir")+passPath;83 new File(destDir).mkdirs();84 String destFile = dateFormat.format(new Date()) + ".png";85 try {86 FileUtils.copyFile(scrFile, new File(destDir + "/" + destFile));87 } catch (IOException e) {88 e.printStackTrace();89 System.out.println("Could not take screenshot on success"+ tr.getInstanceName());//getInstanceName =package+className90 log.debug("Could not take screenshot on success"+ tr.getInstanceName());//getInstanceName =package+className91 }92 Reporter.setEscapeHtml(false);93 Reporter.log("Saved <a href=../screenshot/PASS/" + destFile + ">Screenshot</a>");94 }95 private void log(String string) {96 System.out.print(string);97 if (++m_count % 40 == 0) {98 System.out.println("");99 }100 }101 102 103 public void onFinish(ISuite suite)104 /*every time testng finished running a testsuite it should create a folder - label it with suite name and date of run105 * 106 */107 {108 109 }110}...
Source:CollectionInterfaceImplTest.java
1/*2 * To change this license header, choose License Headers in Project Properties.3 * To change this template file, choose Tools | Templates4 * and open the template in the editor.5 */67package Test;89import org.testng.Assert;10import org.testng.annotations.AfterClass;11import org.testng.annotations.AfterMethod;12import org.testng.annotations.BeforeClass;13import org.testng.annotations.BeforeMethod;14import com.jpretorius.assignment3.CollectionInterface;15import com.jpretorius.assignment3.Impl.CollectionInterfaceImpl;16import org.testng.annotations.Test;17import java.util.ArrayList;18import java.util.HashMap;19import java.util.HashSet;20import java.util.List;21import java.util.Map;22import java.util.Set;2324/**25 *26 * @author user27 */28public class CollectionInterfaceImplTest 29{30 31 public CollectionInterfaceImplTest() 32 {33 34 }3536 @Test37 public void ListOfArrayTest() 38 {39 CollectionInterface collectionInterface = new CollectionInterfaceImpl();40 List result = collectionInterface.ListOfArray();41 System.out.println(result);42 43 List list = new ArrayList();44 list.add("January");45 list.add("February");46 list.add("March");4748 Assert.assertEquals(list, result);49 }50 51 @Test52 public void ListOfMapTest() 53 {54 CollectionInterface collectionInterface = new CollectionInterfaceImpl();55 Map result = collectionInterface.ListOfMap();56 System.out.println(result);57 58 Map map = new HashMap();59 map.put("One", "January");60 map.put("Two", "February");61 map.put("Three", "March");62 Assert.assertEquals(map, result);63 }64 65 @Test66 public void ListOfHashTest() 67 {68 CollectionInterface collectionInterface = new CollectionInterfaceImpl();69 Set result = collectionInterface.ListOfHashSet();70 System.out.println(result);71 72 Set set = new HashSet();73 set.add("Bacon");74 set.add("Egg");75 set.add("Cheese");76 set.add("Toast");7778 Assert.assertEquals(set, result);79 }8081 @BeforeClass82 public static void setUpClass() throws Exception {83 }8485 @AfterClass86 public static void tearDownClass() throws Exception {87 }8889 @BeforeMethod90 public void setUpMethod() throws Exception {91 }9293 @AfterMethod94 public void tearDownMethod() throws Exception {95 }96}
...
Source:ChangeDashboard.java
1package EncorDashboard.TestScripts;23import org.testng.annotations.AfterMethod;4import org.testng.annotations.BeforeMethod;5import org.testng.AssertJUnit;6import org.testng.annotations.AfterMethod;7import org.testng.annotations.BeforeMethod;8import org.testng.AssertJUnit;9import java.io.File;1011import org.openqa.selenium.By;12import org.openqa.selenium.chrome.ChromeDriver;13import org.openqa.selenium.ie.InternetExplorerDriver;14import org.testng.Assert;15import org.testng.annotations.AfterMethod;16import org.testng.annotations.AfterTest;17import org.testng.annotations.BeforeMethod;18import org.testng.annotations.BeforeTest;19import org.testng.annotations.Test;20import EncorDashboard.GlobalLibrary.GlobalFunction;21import EncorDashboard.GlobalLibrary.GlobalVariables;22import EncorDashboard.UserInterface.CreateDashboard;23import EncorDashboard.UserInterface.DashboardGearWheelMenu;24import EncorDashboard.UserInterface.DashboardList;25import org.apache.log4j.Logger;2627public class ChangeDashboard {28 2930 @BeforeMethod31 public void setUp() throws Exception {32 33 GlobalFunction.BrowsersSettings();34 GlobalVariables.oDriver.get(GlobalVariables.LoginURL);35 GlobalVariables.oDriver.manage().window().maximize();36 GlobalFunction.init();37 38 }39 40 //This is test commit41 @Test42 public void ChangeDashboard() throws Exception {43 try44 {45 46 DashboardGearWheelMenu dgwlm = new DashboardGearWheelMenu();47 48 dgwlm.clickonDashboardIcon();49 50 dgwlm.HoveronGearWheel(); 51 52 dgwlm.ClickonChangeDashbd();53 54 Assert.assertEquals(GlobalVariables.oDriver.findElement(By.id("ctl00_IndigoLiteMasterContent_lblDashboardName")).getText(),"HAC(M) :: All Categories"); 55 56 57 }58 catch (Exception e) {59 // TODO: handle exception60 }61 }62 6364 @AfterMethod65 public void tearDown() throws Exception {66 GlobalVariables.oDriver.quit();67 }6869}
...
Source:TestNGConfigurationListener.java
1/*2 * Copyright 2011 the original author or authors.3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.gradle.api.internal.tasks.testing.testng;17import org.testng.ITestResult;18/**19 * Our version of TestNG's IConfigurationListener. Can be adapted to20 * org.testng.internal.IConfigurationListener (from TestNG < 6.2) or21 * org.testng.IConfigurationListener2 (from TestNG >= 6.2). Became22 * necessary because TestNG 6.2 changed the package name of the former23 * interface from org.testng.internal to org.testng.24 * 25 * @see TestNGListenerAdapterFactory26 */27public interface TestNGConfigurationListener {28 /**29 * Invoked whenever a configuration method succeeded.30 */31 void onConfigurationSuccess(ITestResult itr);32 /**33 * Invoked whenever a configuration method failed.34 */35 void onConfigurationFailure(ITestResult itr);36 /**37 * Invoked whenever a configuration method was skipped.38 */39 void onConfigurationSkip(ITestResult itr);40 /**41 * Invoked before a configuration method is invoked. 42 * 43 * Note: This method is only invoked for TestNG 6.2 or higher.44 */45 void beforeConfiguration(ITestResult tr);46}...
Source:StockQuoteAnalyzerTest.java
1import exceptions.InvalidStockSymbolException;2import exceptions.StockTickerConnectionError;3import org.testng.annotations.AfterMethod;4import org.testng.annotations.BeforeMethod;5import static org.mockito.Mockito.mock;6import static org.mockito.Mockito.never;7import static org.mockito.Mockito.times;8import static org.mockito.Mockito.verify;9import static org.mockito.Mockito.when;10import org.mockito.Mock;11import org.testng.annotations.AfterMethod;12import org.testng.annotations.DataProvider;13import org.testng.annotations.Test;14import static org.testng.Assert.*;15public class StockQuoteAnalyzerTest {16 @Mock17 private StockQuoteGeneratorInterface generatorMock;18 @Mock19 private StockTickerAudioInterface audioMock;20 private StockQuoteAnalyzer analyzer;21 @BeforeMethod22 public void setUp() throws Exception {23 generatorMock = mock(StockQuoteGeneratorInterface.class);24 audioMock = mock(StockTickerAudioInterface.class);25 }26 @AfterMethod27 public void tearDown() throws Exception {28 generatorMock = null;29 audioMock = null;30 }31 @Test(expectedExceptions = InvalidStockSymbolException.class)32 public void constructorShouldThrowExceptionWhenSymbolIsInvalid() throws Exception {33 analyzer = new StockQuoteAnalyzer("ZZZZZZZZZ", generatorMock, audioMock);34 }35}...
Source:ITestResultNotifier.java
1package org.testng.internal;2import java.util.List;3import java.util.Set;4import org.testng.IConfigurationListener;5import org.testng.ITestListener;6import org.testng.ITestNGMethod;7import org.testng.ITestResult;8import org.testng.xml.XmlTest;9/**10 * An interface defining the notification for @Test results and also11 * \@Configuration results.12 *13 * @author <a href="mailto:cedric@beust.com">Cedric Beust</a>14 * @author <a href='mailto:the_mindstorm@evolva.ro'>Alexandru Popescu</a>15 */16public interface ITestResultNotifier {17 Set<ITestResult> getPassedTests(ITestNGMethod tm);18 Set<ITestResult> getFailedTests(ITestNGMethod tm);19 Set<ITestResult> getSkippedTests(ITestNGMethod tm);20 void addPassedTest(ITestNGMethod tm, ITestResult tr);21 void addSkippedTest(ITestNGMethod tm, ITestResult tr);22 void addFailedTest(ITestNGMethod tm, ITestResult tr);23 void addFailedButWithinSuccessPercentageTest(ITestNGMethod tm, ITestResult tr);24 void addInvokedMethod(InvokedMethod im);25 XmlTest getTest();26 List<ITestListener> getTestListeners();27 List<IConfigurationListener> getConfigurationListeners();28}...
Source:Listeners.java
1package org.testng.annotations;2import static java.lang.annotation.ElementType.TYPE;3import org.testng.IAnnotationTransformer;4import org.testng.IAnnotationTransformer2;5import org.testng.ITestNGListener;6import java.lang.annotation.Retention;7import java.lang.annotation.Target;8/**9 * This annotation lets you define listeners directly on a test class10 * instead of doing so in your testng.xml. Any class that implements11 * the interface {@link org.testng.ITestNGListener} is allowed,12 * except {@link IAnnotationTransformer} and {@link IAnnotationTransformer2},13 * which need to be defined in XML since they have to be known before we even14 * start looking for annotations.15 *16 * Note that listeners specified this way are global to your entire suite, just17 * like listeners specified in testng.xml.18 *19 * @author Cedric Beust, Mar 26, 201020 *21 */22@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)23@Target({TYPE})24public @interface Listeners {25 Class<? extends ITestNGListener>[] value() default {};26}...
Source:IRemoteSuiteListener.java
1package org.testng.remote.strprotocol;2/**3 * Interface replicating the <code>ISuiteListener</code> used for remote listeners.4 *5 * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a>6 * @see org.testng.ISuiteListener7 */8public interface IRemoteSuiteListener {9 /**10 * General information about the number of suites to be run.11 * This is called once before all suites.12 *13 * @param genericMessage a message containing the number of suites that will be run14 */15 void onInitialization(GenericMessage genericMessage);16 /**17 * @see org.testng.ISuiteListener#onStart(org.testng.ISuite)18 *19 * @param suiteMessage the suite message containing the description of the suite to be run.20 */21 void onStart(SuiteMessage suiteMessage);22 /**23 * @see org.testng.ISuiteListener#onFinish(org.testng.ISuite)24 *25 * @param suiteMessage the suite message containing infos about the finished suite.26 */27 void onFinish(SuiteMessage suiteMessage);28}...
Interface I
Using AI Code Generation
1package testng;2import org.testng.IRetryAnalyzer;3import org.testng.ITestResult;4public class RetryAnalyzer implements IRetryAnalyzer {5int counter = 0;6int retryLimit = 3;7public boolean retry(ITestResult result) {8if(counter < retryLimit) {9counter++;10return true;11}12return false;13}14}15package testng;16import org.testng.ITestContext;17import org.testng.ITestListener;18import org.testng.ITestResult;19public class TestNGListeners implements ITestListener{20public void onTestStart(ITestResult result) {21System.out.println("Test Case Started and details are : "+result.getName());22}23public void onTestSuccess(ITestResult result) {24System.out.println("Test Case Passed and details are : "+result.getName());25}26public void onTestFailure(ITestResult result) {27System.out.println("Test Case Failed and details are : "+result.getName());28}29public void onTestSkipped(ITestResult result) {30System.out.println("Test Case Skipped and details are : "+result.getName());31}32public void onTestFailedButWithinSuccessPercentage(ITestResult result) {33}34public void onStart(ITestContext context) {35}36public void onFinish(ITestContext context) {37}38}39package testng;40import java.lang.reflect.Constructor;41import java.lang.reflect.Method;42import org.testng.IAnnotationTransformer;43import org.testng.annotations.ITestAnnotation;44public class AnnotationTransformer implements IAnnotationTransformer{45public void transform(ITestAnnotation annotation, Class testClass, Constructor testConstructor, Method testMethod) {46annotation.setRetryAnalyzer(testng.RetryAnalyzer.class);47}48}49package testng;50import org.testng.IClassListener;51import org.testng.ITestClass;52public class ClassListener implements IClassListener{53public void onBeforeClass(ITestClass testClass) {54System.out.println("Before class: "+testClass.getName());55}56public void onAfterClass(ITestClass testClass) {57System.out.println("After class: "+testClass.getName());58}59}60package testng;61import java.util.List;62import org.testng.IMethodInstance;63import org.testng.IMethodInterceptor;64import org.testng.ITestContext;65public class MethodInterceptor implements IMethodInterceptor{
Interface I
Using AI Code Generation
1package org.testng;2public interface ITest {3 public String getTestName();4}5package org.testng;6public interface IClass {7 public String getName();8}9package org.testng;10public interface IClassListener {11 public void onBeforeClass(ITestClass testClass);12 public void onAfterClass(ITestClass testClass);13}14package org.testng;15public interface IConfigurable {16 public void run(IHookCallBack callBack, ITestResult testResult);17}18package org.testng;19public interface IHookable {20 public void run(IHookCallBack callBack, ITestResult testResult);21}22package org.testng;23public interface IHookCallBack {24 public void runTestMethod(ITestResult testResult);25}26package org.testng;27public interface IHookable {28 public void run(IHookCallBack callBack, ITestResult testResult);29}30package org.testng;31public interface IInvokedMethod {32 public ITestResult getTestResult();33 public ITestNGMethod getTestMethod();34 public Object getInstance();35 public boolean isTestMethod();36 public boolean isConfigurationMethod();37 public boolean isBeforeMethod();38 public boolean isAfterMethod();39 public boolean isBeforeClass();40 public boolean isAfterClass();41 public boolean isBeforeTest();42 public boolean isAfterTest();43 public boolean isBeforeSuite();44 public boolean isAfterSuite();45}46package org.testng;47public interface IInvokedMethodListener {48 public void beforeInvocation(IInvokedMethod method, ITestResult testResult);49 public void afterInvocation(IInvokedMethod method, ITestResult testResult);50}51package org.testng;52public interface IMethodInterceptor {53 public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context);54}55package org.testng;56public interface IMethodInstance {
Interface I
Using AI Code Generation
1package TestNG;2import org.testng.annotations.Test;3public class TestNGInterface {4 public void test1() {5 System.out.println("test1");6 }7 public void test2() {8 System.out.println("test2");9 }10 public void test3() {11 System.out.println("test3");12 }13}14package TestNG;15import org.testng.annotations.Test;16public class TestNGInterfaceII {17 public void test4() {18 System.out.println("test4");19 }20 public void test5() {21 System.out.println("test5");22 }23 public void test6() {24 System.out.println("test6");25 }26}27package TestNG;28import org.testng.annotations.Test;29public class TestNGInterfaceIII {30 public void test7() {31 System.out.println("test7");32 }33 public void test8() {34 System.out.println("test8");35 }36 public void test9() {37 System.out.println("test9");38 }39}40package TestNG;41import org.testng.annotations.Test;42public class TestNGInterfaceIV {43 public void test10() {44 System.out.println("test10");45 }46 public void test11() {47 System.out.println("test11");48 }49 public void test12() {50 System.out.println("test12");51 }52}53package TestNG;54import org.testng.annotations.Test;55public class TestNGInterfaceV {56 public void test13() {57 System.out.println("test13");58 }59 public void test14() {60 System.out.println("test14");61 }62 public void test15() {63 System.out.println("test15");64 }65}66package TestNG;67import org.testng.annotations.Test;68public class TestNGInterfaceVI {69 public void test16() {70 System.out.println("test16");71 }72 public void test17() {73 System.out.println("test17");74 }75 public void test18() {
Interface I
Using AI Code Generation
1package com.testNG;2import org.testng.annotations.Test;3public class TestNGInterfaceI {4public void testMethodOne() {5System.out.println("TestNGInterfaceI -> testMethodOne");6}7public void testMethodTwo() {8System.out.println("TestNGInterfaceI -> testMethodTwo");9}10}11package com.testNG;12import org.testng.annotations.Test;13public class TestNGInterfaceII {14public void testMethodOne() {15System.out.println("TestNGInterfaceII -> testMethodOne");16}17public void testMethodTwo() {18System.out.println("TestNGInterfaceII -> testMethodTwo");19}20}21package com.testNG;22import org.testng.annotations.Test;23public class TestNGInterfaceIII {24public void testMethodOne() {25System.out.println("TestNGInterfaceIII -> testMethodOne");26}27public void testMethodTwo() {28System.out.println("TestNGInterfaceIII -> testMethodTwo");29}30}31package com.testNG;32import org.testng.annotations.Test;33public class TestNGInterfaceIV {34public void testMethodOne() {35System.out.println("TestNGInterfaceIV -> testMethodOne");36}37public void testMethodTwo() {38System.out.println("TestNGInterfaceIV -> testMethodTwo");39}40}41package com.testNG;42import org.testng.annotations.Test;43public class TestNGInterfaceV {44public void testMethodOne() {45System.out.println("TestNGInterfaceV -> testMethodOne");46}47public void testMethodTwo() {48System.out.println("TestNGInterfaceV -> testMethodTwo");49}50}51package com.testNG;52import org.testng.annotations.Test;53public class TestNGInterfaceVI {54public void testMethodOne() {55System.out.println("TestNGInterfaceVI -> testMethodOne");56}57public void testMethodTwo() {58System.out.println("TestNGInterfaceVI -> testMethodTwo");59}60}61package com.testNG;62import org.testng.annotations.Test;63public class TestNGInterfaceVII {64public void testMethodOne() {65System.out.println("TestNGInterfaceV
Interface I
Using AI Code Generation
1import org.testng.annotations.Test; 2import org.testng.ITestResult; 3import org.testng.IRetryAnalyzer; 4import org.testng.IAnnotationTransformer; 5import org.testng.IAnnotation; 6import org.testng.IClass; 7import org.testng.IClassListener; 8import org.testng.IExecutionListener; 9import org.testng.IInvokedMethod; 10import org.testng.IInvokedMethodListener; 11import org.testng.IMethodInstance; 12import org.testng.IMethodInterceptor; 13import org.testng.IMethodSelector; 14import org.testng.ISuite; 15import org.testng.ISuiteListener; 16import org.testng.ISuiteResult;
1package com.test;23public class Main {45 public static void main(String[] args) {6 System.out.println("salam 2nya\n");7 }8}9
1javac HelloWorld.java2java -cp . HelloWorld3
TestNG is a Java-based open-source framework for test automation that includes various test types, such as unit testing, functional testing, E2E testing, etc. TestNG is in many ways similar to JUnit and NUnit. But in contrast to its competitors, its extensive features make it a lot more reliable framework. One of the major reasons for its popularity is its ability to structure tests and improve the scripts' readability and maintainability. Another reason can be the important characteristics like the convenience of using multiple annotations, reliance, and priority that make this framework popular among developers and testers for test design. You can refer to the TestNG tutorial to learn why you should choose the TestNG framework.
You can push your abilities to do automated testing using TestNG and advance your career by earning a TestNG certification. Check out our TestNG certification.
Watch this complete tutorial to learn how you can leverage the capabilities of the TestNG framework for Selenium automation testing.
Get 100 minutes of automation test minutes FREE!!