Best Testng code snippet using org.testng.TestRunner.getCurrentXmlTest
Source:BaseTest.java  
...124	public void setUpSuite(final ITestContext context) {125		PropertyConfigurator.configure(log4jPath);126		String testSetNum;127		String globalTestSetNum;128		baseBrowser = context.getCurrentXmlTest().getParameter("runBrowser");129		baseUrl = context.getCurrentXmlTest().getParameter("runUrl");130		if (context.getCurrentXmlTest().getParameter("globalEnvironment") == null) {131			environmentName = context.getCurrentXmlTest().getParameter("environment");132		} else {133			environmentName = context.getCurrentXmlTest().getParameter("globalEnvironment");134		}135		testSetPath = context.getCurrentXmlTest().getParameter("testSetPath");136		testSetName = context.getCurrentXmlTest().getParameter("testSetName");137		testSetNum = context.getCurrentXmlTest().getParameter("testSetNumber");138		globalTestSetPath = context.getCurrentXmlTest().getParameter("globalTestSetPath");139		globalTestSetName = context.getCurrentXmlTest().getParameter("globalTestSetName");140		globalTestSetNum = context.getCurrentXmlTest().getParameter("globalTestSetNumber");141		if ("".equals(globalTestSetNum) || globalTestSetNum == null) {142			if ("".equals(testSetNum) || testSetNum == null) {143				testSetPath = defaultTestSetPath;144				testSetName = defaultTestSetName;145				testSetNumber = defaultTestSetNumber;146			} else {147				testSetNumber = Integer.parseInt(testSetNum);148			}149		} else {150			testSetPath = globalTestSetPath;151			testSetName = globalTestSetName;152			testSetNumber = Integer.parseInt(globalTestSetNum);153		}154		switch (environmentName) {155		default:156		case "SIT1":157			environmentURL = sit1EnvURL;158			break;159		case "SIT2":160			environmentURL = sit2EnvURL;161			break;162		case "TRAIN":163			environmentURL = trainingEnvURL;164			break;165		case "DEV":166			environmentURL = devEnvURL;167			break;168		case "PREPROD":169			environmentURL = preProdEnvURL;170			break;171		case "EASE":172			environmentURL = easeEnvURL;173			break;174		case "MG2":175			environmentURL = mg2EnvURL;176			break;177		}178		loginPg = PageFactory.initElements(driver, TEMENOS_LoginPage.class);179		homePg = PageFactory.initElements(driver, TEMENOS_HomePage.class);180		listTable = PageFactory.initElements(driver, TEMENOS_ListTable.class);181		inputTable = PageFactory.initElements(driver, TEMENOS_InputTable.class);182		readTable = PageFactory.initElements(driver, TEMENOS_ReadTable.class);183		compositeScreen = PageFactory.initElements(driver, TEMENOS_CompositeScreen.class);184		versionScreen = PageFactory.initElements(driver, TEMENOS_VersionScreen.class);185		toolElements = PageFactory.initElements(driver, TEMENOS_Tools.class);186		toolbarElements = PageFactory.initElements(driver, TEMENOS_Toolbars.class);187		enquiryElements = PageFactory.initElements(driver, TEMENOS_Enquiry.class);188		mainMenu = PageFactory.initElements(driver, TEMENOS_MainMenu.class);189		subMenu = PageFactory.initElements(driver, TEMENOS_SubMenu.class);190		tabbedScreen = PageFactory.initElements(driver, TEMENOS_TabbedScreen.class);191	}192	@BeforeSuite(enabled = false, alwaysRun = false)193	public void removeExistingProcesses() throws InterruptedException, IOException {194		Runtime.getRuntime().exec("taskkill /F /IM IEDriverServer.exe");195		Runtime.getRuntime().exec("taskkill /F /IM iexplore.exe");196	}197	@BeforeClass(alwaysRun = true)198	@Parameters({ "runBrowser", "runUrl", "env", "enableNativeEvents", "persistentHovering", "requireWindowFocus" })199	public void setUpBrowser(final String runBrowser, final String runUrl, final ITestContext ctx,200			@Optional("") final String env, @Optional("FALSE") final String enableNativeEvents,201			@Optional("FALSE") final String persistentHovering, @Optional("FALSE") final String requireWindowFocus) {202		baseEnv = env;203		baseEnableNativeEvents = enableNativeEvents;204		basePersistentHovering = persistentHovering;205		baseRequireWindowFocus = requireWindowFocus;206		// Setting up worksheet207		if ("".equals(baseEnv)) {208			Reporter.log("environment parameter not defined in TestNG suite file. Using ENV1 environment as default",209					false);210			baseEnv = "ENV1";211		} else {212			baseEnv = ctx.getCurrentXmlTest().getParameter("env").toUpperCase().trim();213			Reporter.log("Environment set to: " + baseEnv, false);214		}215		if ("FALSE".equals(baseEnableNativeEvents)) {216			Reporter.log("Native Events not defined in TestNG suite file. Using FALSE as default", false);217		} else {218			baseEnableNativeEvents = ctx.getCurrentXmlTest().getParameter("enableNativeEvents").toUpperCase().trim();219			Reporter.log("Native Events set to: " + baseEnableNativeEvents, false);220		}221		if ("FALSE".equals(basePersistentHovering)) {222			Reporter.log("Persistent Hovering parameter not defined in TestNG suite file. Using FALSE as default",223					false);224		} else {225			basePersistentHovering = ctx.getCurrentXmlTest().getParameter("persistentHovering").toUpperCase().trim();226			Reporter.log("Persistent Hovering set to: " + baseEnableNativeEvents, false);227		}228		if ("FALSE".equals(baseRequireWindowFocus)) {229			Reporter.log("Requires Window Focus parameter not defined in TestNG suite file. Using FALSE as default",230					false);231		} else {232			baseRequireWindowFocus = ctx.getCurrentXmlTest().getParameter("requireWindowFocus").toUpperCase().trim();233			Reporter.log("Require Window Focus set to: " + baseRequireWindowFocus, false);234		}235		launchBrowser(baseBrowser, baseUrl);236		final TestRunner runner = (TestRunner) ctx;237		runner.setOutputDirectory(outputDirectory);238		Reporter.log("Application Launched successfully", false);239		driver.manage().timeouts().implicitlyWait(elementWaitTimeout / 5, TimeUnit.SECONDS);240	}241	public static WebDriver launchBrowser(final String runBrowser, final String runUrl) {242		final Path currentRelPath = Paths.get("");243		projectPath = currentRelPath.toAbsolutePath().toString();244		final String baseBrowser1 = runBrowser.toLowerCase(Locale.ENGLISH).trim();245		final String baseUrl1 = runUrl;246		DesiredCapabilities capabilities;...Source:AbstractTestListeners.java  
...113    {114        LOG.info( "onTestSuccess " + result.getTestContext().getName() );115        String className = result.getMethod().getTestClass().getName();116        className = className.substring( className.lastIndexOf( '.' ) + 1 );117        LOG.info( "<<" + result.getTestContext().getCurrentXmlTest().getName() + ">> <<PASSED>> <<" + className + ">> << * >>" );118        /**119         * call backs120         */121        for( ITestListeners listener : m_listeners )122        {123            listener.onTestSuccess( result );124        }125    }126    @Override127    public void onTestFailure( ITestResult result )128    {129        LOG.info( "onTestFailure " + result.getTestContext().getName() );130        String className = result.getMethod().getTestClass().getName();131        className = className.substring( className.lastIndexOf( '.' ) + 1 );132        LOG.info( "<<" + result.getTestContext().getCurrentXmlTest().getName() + ">> <<FAILED>> <<" + className + ">> <<" + Utility.getErrorType() + ">>" );133        /**134         * call backs135         */136        for( ITestListeners listener : m_listeners )137        {138            listener.onTestFailure( result );139        }140    }141    @Override142    public void onTestSkipped( ITestResult result )143    {144        LOG.info( "onTestSkipped " + result.getTestContext().getName() );145        String className = result.getMethod().getTestClass().getName();146        className = className.substring( className.lastIndexOf( '.' ) + 1 );147        LOG.info( "<<" + result.getTestContext().getCurrentXmlTest().getName() + ">> <<SKIPPED>> <<" + className + ">> <<" + Utility.getErrorType() + ">>" );148        /**149         * call backs150         */151        for( ITestListeners listener : m_listeners )152        {153            listener.onTestSkipped( result );154        }155    }156    @Override157    public void onTestFailedButWithinSuccessPercentage( ITestResult result )158    {}159    @Override160    public void onFinish( ITestContext context )161    {...Source:TypeValidation.java  
...47    public void typeLabels(final ITestContext _context)48    {49        try {50            final SoftAssert softAssert = new SoftAssert();51            final String ciClass = _context.getCurrentXmlTest().getParameter("ciClass");52            final String regex4TypeLabelExclude = _context.getCurrentXmlTest().getParameter("regex4TypeLabelExclude");53            if (ciClass != null) {54                Pattern pattern = null;55                if (regex4TypeLabelExclude != null) {56                    pattern = Pattern.compile(regex4TypeLabelExclude);57                }58                final Class<?> clazz = Class.forName(ciClass);59                final Map<String, org.efaps.tests.ci.digester.CIType> mapping = new HashMap<>();60                for (final org.efaps.tests.ci.digester.CIType type : AbstractCIDataProvider.TYPES) {61                    mapping.put(type.getUuid(), type);62                }63                for (final Field field : clazz.getDeclaredFields()) {64                    if (Modifier.isStatic(field.getModifiers())) {65                        final Object typeObj = field.get(null);66                        if (typeObj instanceof CIType) {...Source:RunCukesByFeatureAndCompositionTest1.java  
...48	// Method handleTestMethodInformation requires 3 parameters but 0 were49	// supplied in the @Configuration annotation.50	public void handleTestMethodInformation(final ITestContext context,51			/* final IDataProvidable testAnnotation, */ final Method method) {52		final String suiteName = context.getCurrentXmlTest().getSuite().getName();53		final String methodName = method.getName();54		final String testName = context.getCurrentXmlTest().getName();55		System.err.println(String.format(56				"BeforeMethod:\tSuite: \"%s\"\tTest: \"%s\"\tMethod: \"%s\"", suiteName,57				testName, methodName));58		/*59		String dataProvider = ((IDataProvidable) testAnnotation).getDataProvider();60		System.err.println("Data Provider of the method: " + dataProvider);61		*/62		@SuppressWarnings("deprecation")63		final Map<String, String> parameters = (((TestRunner) context).getTest())64				.getParameters();65		final Set<String> keys = parameters.keySet();66		if (keys.size() == 0) {67			System.err.println("Method has no parameters");68		} else {
...Source:SwiftTestRunner.java  
...37	public void beforeSuite(ITestContext context){38		log.info("Initializing suite...");39		Controller.getController().startSuite();40		log.info("Started: " + Controller.getController().getCurrentSuite().getStarted());41		String suiteName = context.getCurrentXmlTest().getSuite().getName();42		log.debug("Suite: " + suiteName);43		Controller.getController().getCurrentSuite().setName(suiteName);44	}45	46	@BeforeClass47	public void beforeClass(){48		String className = this.getClass().getName();49		50		log.debug("Test: " + className);51		test.setName(className);52	}53	54	@Parameters({ "browser", "ip", "platform", "version" })55	@BeforeTest56	public void beforeTest(@Optional("") String browser, @Optional("") String ip, @Optional("") String platform,57			@Optional("") String version, ITestContext context) throws MalformedURLException{58		test = Controller.getController().getCurrentSuite().startTest();59		60		driver = seleniumUtil.setup(browser, ip, version, version);61		driver.manage().timeouts()62		.implicitlyWait(BaseConfig.EXECUTION_WAIT_IN_MILLISECONDS, TimeUnit.MILLISECONDS);63		seleniumUtil.launchBrowser(driver);64	}65	66	@BeforeMethod67	public void beforeMethod(ITestContext context) throws Exception{68		//TODO69	}70	71	@AfterMethod72	public void afterMethod(ITestResult testResult) throws Exception{73		String runName = testResult.getTestContext().getCurrentXmlTest().getClass().getSimpleName();74		test.getCurrentRun().setName(runName);75		76		Status status = Status.get(testResult.getStatus());77		test.getCurrentRun().set("status",status.name());78		Controller.getController().insertRunRecord();79		80	}81	@AfterTest82	public void close(ITestContext tc) throws ParseException {83		84		Test test = Controller.getController().getCurrentSuite().getCurrentTest();85		86		test.setNumFailed(tc.getFailedTests().getAllResults().size());87		test.setNumPassed(tc.getPassedTests().getAllResults().size());...Source:CSVProviderTest.java  
...38	// supplied in the @Configuration annotation.39	@BeforeMethod40	public void handleTestMethodInformation(final ITestContext context,41			final Method method) {42		final String suiteName = context.getCurrentXmlTest().getSuite().getName();43		final String methodName = method.getName();44		final String testName = context.getCurrentXmlTest().getName();45		System.err.println("BeforeMethod Suite: " + suiteName);46		System.err.println("BeforeMethod Test: " + testName);47		System.err.println("BeforeMethod Method: " + methodName);48		// String dataProvider = ((IDataProvidable)annotation).getDataProvider();49		// System.err.println("Data Provider: " + dataProvider);50		@SuppressWarnings("deprecation")51		final Map<String, String> parameters = (((TestRunner) context).getTest())52				.getParameters();53		final Set<String> keys = parameters.keySet();54		for (String key : keys) {55			System.err.println(56					"BeforeMethod Parameter: " + key + " = " + parameters.get(key));57		}58		final Set<java.lang.String> attributeNames = ((IAttributes) context)...Source:ContextManager.java  
...53			threadLevelContext.get().buildTestContext(context);54		}55	}56	public static void initTestLevelContext(ITestContext context) {57		testLevelContext.put(context.getCurrentXmlTest(),58				new TestContext());59		testLevelContext.get(context.getCurrentXmlTest()).buildTestLevelContext(60				context);61	}62	public static TestContext getGlobalContext() {63		return globalContext;64	}65	public static TestContext getThreadLevelContext() {66		return threadLevelContext.get();67	}68	public static TestContext getTestLevelContext() {69		return testLevelContext.get(((ITestContext) getThreadLevelContext()70				.getParameter(TestContext.TESTNG_CONTEXT))71				.getCurrentXmlTest());72	}73	public static TestContext getTestLevelContext(ITestContext context) {74		return testLevelContext.get(context.getCurrentXmlTest());75	}76}...Source:TestRunner.java  
...19    }20    @BeforeSuite21    public void beforeTest(ITestContext context) {22        context.getSuite().getXmlSuite().setDataProviderThreadCount(Integer.parseInt(System.getProperty("threads")));23        context.getCurrentXmlTest().setName("Test Runner");24        context.getCurrentXmlTest().getSuite().setName("Test Suite");25    }26    }...getCurrentXmlTest
Using AI Code Generation
1TestRunner runner = (TestRunner) Reporter.getCurrentTestResult().getTestContext();2XmlTest currentXmlTest = runner.getCurrentXmlTest();3String testSuiteName = currentXmlTest.getSuite().getName();4String testName = currentXmlTest.getName();5System.out.println("Test Suite Name: " + testSuiteName);6System.out.println("Test Name: " + testName);getCurrentXmlTest
Using AI Code Generation
1package com.example.test;2import org.testng.TestRunner;3import org.testng.annotations.Test;4public class TestRunnerTest {5    public void testGetCurrentXmlTest() {6        TestRunner testRunner = new TestRunner();7        System.out.println("Current XML Test: " + testRunner.getCurrentXmlTest());8    }9}getCurrentXmlTest
Using AI Code Generation
1import org.testng.TestRunner2import org.testng.TestNG3import org.testng.ITestResult4import org.testng.ITestContext5import org.testng.ITestListener6import org.testng.ITestNGMethod7import org.testng.annotations.Test8import org.testng.annotations.BeforeTest9import org.testng.annotations.AfterTest10import org.testng.annotations.BeforeSuite11import org.testng.annotations.AfterSuite12import org.testng.annotations.BeforeClass13import org.testng.annotations.AfterClass14import org.testng.annotations.BeforeMethod15import org.testng.annotations.AfterMethod16import org.testng.annotations.DataProvider17import org.testng.annotations.Factory18import org.testng.annotations.Parameters19import org.testng.annotations.BeforeGroups20import org.testng.annotations.AfterGroups21import org.testng.annotations.Listeners22import org.testng.annotations.BeforeSuite23import org.testng.annotations.AfterSuite24import org.testng.annotations.BeforeGroups25import org.testng.annotations.AfterGroups26import org.testng.annotations.BeforeClass27import org.testng.annotations.AfterClass28import org.testng.annotations.BeforeMethod29import org.testng.annotations.AfterMethod30import org.testng.annotations.DataProvider31import org.testng.annotations.Factory32import org.testng.annotations.Parameters33import org.testng.annotations.BeforeGroups34import org.testng.annotations.AfterGroups35import org.testng.annotations.Listeners36import org.testng.annotations.BeforeSuite37import org.testng.annotations.AfterSuite38import org.testng.annotations.BeforeGroups39import org.testng.annotations.AfterGroups40import org.testng.annotations.BeforeClass41import org.testng.annotations.AfterClass42import org.testng.annotations.BeforeMethod43import org.testng.annotations.AfterMethod44import org.testng.annotations.DataProvider45import org.testng.annotations.Factory46import org.testng.annotations.Parameters47import org.testng.annotations.BeforeGroups48import org.testng.annotations.AfterGroups49import org.testng.annotations.Listeners50import org.testng.annotations.BeforeSuite51import org.testng.annotations.AfterSuite52import org.testng.annotations.BeforeGroups53import org.testng.annotations.AfterGroups54import org.testng.annotations.BeforeClass55import org.testng.annotations.AfterClass56import org.testng.annotations.BeforeMethod57import org.testng.annotations.AfterMethod58import org.testng.annotations.DataProvider59import org.testng.annotations.Factory60import org.testng.annotations.Parameters61import org.testng.annotations.BeforeGroups62import org.testng.annotations.AfterGroups63import org.testng.annotations.Listeners64import org.testng.annotations.BeforeSuite65import org.testng.annotations.AfterSuite66import org.testng.annotations.BeforeGroups67import org.testng.annotations.AfterGroups68import org.testng.annotations.BeforeClass69import org.testng.annotations.AfterClass70import org.testng.annotations.BeforeMethod71import org.testng.annotations.AfterMethod72import org.testng.annotationsgetCurrentXmlTest
Using AI Code Generation
1public void getCurrentTestName() {2    String currentTestName = TestRunner.getCurrentXmlTest().getName();3    System.out.println(currentTestName);4}5public void getCurrentTestParameters() {6    Map<String, String> currentTestParameters = TestRunner.getCurrentXmlTest().getAllParameters();7    System.out.println(currentTestParameters);8}9public void getCurrentTestGroups() {10    Collection<String> currentTestGroups = TestRunner.getCurrentXmlTest().getIncludedGroups();11    System.out.println(currentTestGroups);12}13public void getCurrentTestClasses() {14    Collection<XmlClass> currentTestClasses = TestRunner.getCurrentXmlTest().getXmlClasses();15    System.out.println(currentTestClasses);16}17public void getCurrentTestSuites() {18    Collection<XmlSuite> currentTestSuites = TestRunner.getCurrentXmlTest().getSuites();19    System.out.println(currentTestSuites);20}21public void getCurrentTestListeners() {22    Collection<XmlClass> currentTestListeners = TestRunner.getCurrentXmlTest().getListenerClasses();23    System.out.println(currentTestListeners);24}25public void getCurrentTestMethods() {26    Collection<XmlInclude> currentTestMethods = TestRunner.getCurrentXmlTest().getIncludedMethods();27    System.out.println(currentTestMethods);28}29public void getCurrentTestMethods() {30    Collection<XmlInclude> currentTestMethods = TestRunner.getCurrentXmlTest().getIncludedMethods();31    System.out.println(currentTestMethods);32}33public void getCurrentTestDescription()getCurrentXmlTest
Using AI Code Generation
1package com.automationpractice;2import java.io.File;3import java.io.IOException;4import java.util.ArrayList;5import java.util.List;6import java.util.logging.FileHandler;7import java.util.logging.Level;8import java.util.logging.Logger;9import java.util.logging.SimpleFormatter;10import org.testng.ITestContext;11import org.testng.ITestListener;12import org.testng.ITestResult;13public class TestListener implements ITestListener {14	private static Logger log = Logger.getLogger("MyLog");15	private static FileHandler fh;16	public void onTestStart(ITestResult result) {17		String testName = result.getName();18		try {19			fh = new FileHandler("C:\\Users\\anand\\eclipse-workspace\\AutomationPractice\\test-output\\" + testName + ".log");20			log.addHandler(fh);21			SimpleFormatter formatter = new SimpleFormatter();22			fh.setFormatter(formatter);23			log.info("Test Started");24		} catch (SecurityException e) {25			e.printStackTrace();26		} catch (IOException e) {27			e.printStackTrace();28		}29	}30	public void onTestSuccess(ITestResult result) {31		log.info("Test Passed");32		fh.close();33	}34	public void onTestFailure(ITestResult result) {35		log.info("Test Failed");36		fh.close();37	}38	public void onTestSkipped(ITestResult result) {39		log.info("Test Skipped");40		fh.close();41	}42	public void onTestFailedButWithinSuccessPercentage(ITestResult result) {43	}44	public void onStart(ITestContext context) {45	}46	public void onFinish(ITestContext context) {47	}48}getCurrentXmlTest
Using AI Code Generation
1public void getCurrentTestListeners() {2    Collection<XmlClass> currentTestListeners = TestRunner.getCurrentXmlTest().getListenerClasses();3    System.out.println(currentTestListeners);4}5public void getCurrentTestMethods() {6    Collection<XmlInclude> currentTestMethods = TestRunner.getCurrentXmlTest().getIncludedMethods();7    System.out.println(currentTestMethods);8}9public void getCurrentTestMethods() {10    Collection<XmlInclude> currentTestMethods = TestRunner.getCurrentXmlTest().getIncludedMethods();11    System.out.println(currentTestMethods);12}13public void getCurrentTestDescription()getCurrentXmlTest
Using AI Code Generation
1public void getCurrentTestName() {2    String currentTestName = TestRunner.getCurrentXmlTest().getName();3    System.out.println(currentTestName);4}5public void getCurrentTestParameters() {6    Map<String, String> currentTestParameters = TestRunner.getCurrentXmlTest().getAllParameters();7    System.out.println(currentTestParameters);8}9public void getCurrentTestGroups() {10    Collection<String> currentTestGroups = TestRunner.getCurrentXmlTest().getIncludedGroups();11    System.out.println(currentTestGroups);12}13public void getCurrentTestClasses() {14    Collection<XmlClass> currentTestClasses = TestRunner.getCurrentXmlTest().getXmlClasses();15    System.out.println(currentTestClasses);16}17public void getCurrentTestSuites() {18    Collection<XmlSuite> currentTestSuites = TestRunner.getCurrentXmlTest().getSuites();19    System.out.println(currentTestSuites);20}21public void getCurrentTestListeners() {22    Collection<XmlClass> currentTestListeners = TestRunner.getCurrentXmlTest().getListenerClasses();23    System.out.println(currentTestListeners);24}25public void getCurrentTestMethods() {26    Collection<XmlInclude> currentTestMethods = TestRunner.getCurrentXmlTest().getIncludedMethods();27    System.out.println(currentTestMethods);28}29public void getCurrentTestMethods() {30    Collection<XmlInclude> currentTestMethods = TestRunner.getCurrentXmlTest().getIncludedMethods();31    System.out.println(currentTestMethods);32}33public void getCurrentTestDescription()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!!
