Best Testng code snippet using org.testng.TestRunner.getOutputDirectory
Source:TestNgUnit.java  
...41        testNG = new TestNG();42        TestRunner runner = (TestRunner) ctx;43        testNG.setUseDefaultListeners(false);44        testNG.initializeEverything();45        System.out.println("TestNG out: " + testNG.getOutputDirectory());46 //       ArrayList<String> alRptogs = new ArrayList();47 //       gbl99.setAlReporterEntries(alRptogs);48        System.out.println("in beforeSuite");49        System.out.println("Current Dir: " + nom99.GetWorkingDirectory());50 //       File wf = new File(nom99.GetWorkingDirectory());51 //       File fFeatureTemplates = new File("src/test/resources/features");52 //       File fFeatureGened =new File(fFeatureTemplates.getAbsolutePath() + File.separator + "Gened");53 //       fFeatureGened.mkdirs();54 //       File faFt[] = fFeatureTemplates.listFiles();55 //       for(int i=0; i < faFt.length; i++)56 //       {57 //           System.out.println("File " + i + " name: " + faFt[i].getName());58 //           if(!faFt[i].isDirectory()) {59 //               LineReader lr = new LineReader(faFt[i].getAbsolutePath());60 //               LineWriter lw = new LineWriter(fFeatureGened.getAbsolutePath() + File.separator + faFt[i].getName());61 //               ArrayList<String> alFt = lr.ReadAllLines();62 //               for (int i4 = 0; i4 < alFt.size(); i4++) {63 //                   System.out.println(alFt.get(i4));64 //                   lw.WriteLine((alFt.get(i4)));65 //               }66 //               System.out.println("");67 //               System.err.println(" End File &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");68 //               System.out.println();69 //           }70 //       }71        System.out.println("Exit Before Suite");72    }73    @AfterSuite(alwaysRun = true)74    public void afterSuite() {75        System.out.println("in After Suite " + gbl99.isbDetailLog());76        System.err77                .println("************************************************************************************************");78        System.err79                .println("************************************************************************************************");80        System.err81                .println("************************************************************************************************");82        System.err83                .println("************************************************************************************************");84        Reporter.setEscapeHtml(false);85//		Rpt.log(sLog);86        ArrayList<String> alLogs = gbl99.getAlReporterEntries();87        String sAll = "";88        System.out.println("Log Count: " + alLogs.size());89        for(int i88 = 0; i88 < alLogs.size(); i88++)90        {91            System.out.println(alLogs.get(i88));92            sAll = sAll + alLogs.get(i88);93        }94        List<String> lsOut = Reporter.getOutput();95        System.out.println("Reporter Output before: A" );96        for(int i8=0; i8<lsOut.size(); i8++)97        {98            System.out.println("Reporter Output before: " + lsOut.get(i8));99        }100        System.out.println("Reporter Output before: Z" );101        System.out.println("Reporter Output before: Z2 \n " + sAll );102        Reporter.clear();103        Reporter.log("");104        lsOut = Reporter.getOutput();105        System.out.println("Reporter Output before: A" );106        String sY="";107        for(int i8=0; i8<lsOut.size(); i8++)108        {109            String sT =  lsOut.get(i8);110            while(sT.indexOf("=")>=0) sT = sT.replace("=", "");111            while(sT.indexOf("(+0)")>=0) sT = sT.replace("(+0)", "");112            while(sT.indexOf("(+1)")>=0) sT = sT.replace("(+1)", "");113            while(sT.indexOf("(+2)")>=0) sT = sT.replace("(+2)", "");114            sY = sY + sT;115            System.out.println("Reporter Output beforeZZ: " + lsOut.get(i8));116        }117        System.out.println("Pass/Fail: " + sY);118        sY = sY.replace("Total", "");119        sY = sY.replace("Failures", "Failed");120        sY = sY.replace("Skips", "Skipped");121        sAll = "<h3>" + sY + "</h3><BR>" + sAll;122        try {123            Reporter.log("Stuff");124            Reporter.clear();125            Reporter.log(sAll);126            System.out.println("Reporter loggged");127        } catch (Exception e2) {128            // TODO Auto-generated catch block129            e2.printStackTrace();130        }131        Desktop d = Desktop.getDesktop();132        System.out.println("Test Dir: " + gbl99.getTestContext().getSuite().getOutputDirectory());133        System.out.println("Results Dir: " + gbl99.getHtmlResultsLog().getsResultsFldr());134        System.out.println("Events Dir: " + gbl99.getHtmleventslogging().getsResultsFldr());135        System.out.println("Current Dir: " + nom99.GetWorkingDirectory());136        String sFCurrent = System.getProperty("user.dir") + File.separator + "test-output";137        String sNewFTestNGLoc = nom99.GetWorkingDirectory().substring(0, nom99.GetWorkingDirectory().length()-2)  + File.separator + "test-output_" + gbl99.getTestContext().getSuite().getName() + "_" + nom99.ReplaceHardTags("[~Dateyyyymmddhhmmssmm~]");138        String sOldFTestNGLoc = nom99.GetWorkingDirectory().substring(0, nom99.GetWorkingDirectory().length()-2)  + File.separator + "test-output";139        String sFTestNGLoc =  nom99.GetWorkingDirectory().substring(0, nom99.GetWorkingDirectory().length()-2)  + File.separator + "test-output"+ File.separator + "html" + File.separator + "index.html";140        System.out.println("Working: " + nom99.GetWorkingDirectory());141        System.out.println("TestNG LOC: " + sFTestNGLoc);142        System.out.println("sOldFTestNGLoc: " + sOldFTestNGLoc);143        System.out.println(gbl99.getTestContext().getOutputDirectory());144        System.out.println("sNewFTestNGLoc: " + sNewFTestNGLoc);145        TestRunner runner = (TestRunner) gbl99.getTestContext();146        //    runner.setOutputDirectory("/Path/To/Store/Output");147        System.out.println("Output Dir: " + runner.getOutputDirectory());148//	try {149//		System.in.read();150//	} catch (IOException e) {151//		// TODO Auto-generated catch block152//		e.printStackTrace();153//	}154        String sTestNGLoc = "file:///" + sFTestNGLoc;155        sTestNGLoc = sTestNGLoc.replace("\\", "/");156        sTestNGLoc = sTestNGLoc.replaceAll(" ", "%20");157        System.out.println("TestNGLoc: " + sTestNGLoc);158       File fNew = new File(sNewFTestNGLoc);159//        fNew.mkdirs();160//        File fOld = new File(sOldFTestNGLoc);161//        nom99.copyDirectory(fOld, fNew);...Source:AbstractTestListeners.java  
...40         */41        if( LocalCommandLineArgs.instance().isNative )42        {43            String username = StringUtils.isEmpty( LocalCommandLineArgs.instance().username ) ? "" : "_" + LocalCommandLineArgs.instance().username;44            m_logPath = suite.getOutputDirectory() + File.separator + Utility.getTime( "yyyyMM" + File.separator + "yyyyMMddHHmmss" + username ) + File.separator;45        }46        else47        {48            m_logPath = LocalCommandLineArgs.instance().logPath;49        }50        LOG = TestLogger.setupLogger( m_logPath, this.getClass() );51        LOG.info( "TestNG executed with log directory " + m_logPath );52        LOG.info( "onStart ISuite " + suite.getName() );53        Configuration.SUITE_NAME = suite.getName();54        /**55         * member listeners initialization56         */57        addListeners( m_listeners );58        LOG.info( "Executing : " + suite.getXmlSuite().getTests().size() + " test cases" );59        /**60         * call backs61         */62        for( ITestListeners listener : m_listeners )63        {64            listener.onStart( suite );65        }66        if( TestApiObject.instance().bool( TestApiParameters.API_PROFILE_LISTENER ) )67        {68            m_listeners.add( new ProfilerListener() );69            new ProfilerListener().onStart( suite );70        }71    }72    public abstract void addListeners( List< ITestListeners > listeners );73    @Override74    public void onStart( ITestContext context )75    {76        // test case log starts here77        Reporter.clear();78        LOG.info( "onStart ITestContext " + context.getName() );79        // this is only required by getting snapshot from base test80        // when configuration has been implemented81        // there won't be any use of this code block82        LOG.info( "context output directory " + context.getOutputDirectory() );83        TestRunner runner = (TestRunner)context;84        runner.setOutputDirectory( m_logPath );85        LOG.info( "context changed output directory " + context.getOutputDirectory() );86        // reset test case time87        Utility.resetReferenceTime();88        /**89         * call backs90         */91        for( ITestListeners listener : m_listeners )92        {93            listener.onStart( context );94        }95    }96    @Override97    public void onTestStart( ITestResult result )98    {99        LOG.debug( "onTestStart " + result.getTestContext().getName() );...Source:CommonClass.java  
...54	{55		DOMConfigurator.configure("log4j.xml");56		log.info("Before suite launch...");57		TestRunner runner = (TestRunner) ctx;58		OUTPUT_PATH = (new File(runner.getOutputDirectory())).getParent();59		IMAGES_PATH = new File(runner.getOutputDirectory()).getParent() + "_Images\\";60		//Globals variables populated here --- START ---61		CommonClass.bRunInTestMode 		= bRunInTestMode;62		CommonClass.bPrintScreen 		= bPrintScreen;63		CommonClass.CHROME_DRIVER_PATH	= CHROME_DRIVER_PATH;64		CommonClass.IE_DRIVER_PATH 		= IE_DRIVER_PATH;65		CommonClass.OUTPUT_PATH 		= OUTPUT_PATH;66		CommonClass.IMAGES_PATH 		= IMAGES_PATH;67		CommonClass.iWaitForElement 	= iWaitForElement;68		CommonClass.iWaitForThread 		= iWaitForThread;69		CommonClass.iWaitForThread1 	= iWaitForThread1;70		CommonClass.iWaitForThread2 	= iWaitForThread2;71		CommonClass.sBaseURL			= sBaseURL;72		//Globals variables populated here ---  END  ---73		...Source:SeleneseTestNgHelper.java  
...63    }64    Selenium screenshotTaker = new DefaultSelenium(host, Integer.parseInt(port),65        "", "");66    TestRunner tr = (TestRunner) context;67    File outputDirectory = new File(context.getOutputDirectory());68    tr.addListener((IResultListener) new ScreenshotListener(outputDirectory,69        screenshotTaker));70  }71  @AfterMethod72  @Override73  public void checkForVerificationErrors() {74    super.checkForVerificationErrors();75  }76  @AfterMethod(alwaysRun = true)77  public void selectDefaultWindow() {78    if (selenium != null) {79      selenium.selectWindow("null");80    }81  }...Source:TestRunner.java  
...44        TestConfiguration config = TestConfiguration.getInstance();45        if (!StringUtils.isEmpty(cliArguments.getTestType())) {46            config.setTestType(cliArguments.getTestType());47        }48        if (!StringUtils.isEmpty(cliArguments.getOutputDirectory())) {49            config.setOutputDir(new File(cliArguments.getOutputDirectory()));50        }51        if (!StringUtils.isEmpty(cliArguments.getAppUnderTestPath())) {52            File classpathRoot = new File(System.getProperty("user.dir"));53            config.setAppUnderTestPath(new File(cliArguments.getAppUnderTestPath()).getAbsolutePath());54        }55        if (!StringUtils.isEmpty(cliArguments.getAppiumUrl())) {56            config.setAppiumServerUrl(new URL(cliArguments.getAppiumUrl()));57        }58        return config;59    }60    private static String getAbsolutePath(String filePath) {61        return new File(filePath).getAbsolutePath();62    }63}...getOutputDirectory
Using AI Code Generation
1package com.javacodegeeks.testng;2import java.io.File;3import org.testng.ITestResult;4import org.testng.TestListenerAdapter;5public class CustomListener extends TestListenerAdapter {6    public void onTestFailure(ITestResult tr) {7        super.onTestFailure(tr);8        String outputDirectory = tr.getTestContext().getOutputDirectory();9        System.out.println("outputDirectory: " + outputDirectory);10    }11}12package com.javacodegeeks.testng;13import org.testng.annotations.Test;14public class TestClass {15    public void testMethod() {16        System.out.println("testMethod");17    }18}getOutputDirectory
Using AI Code Generation
1package com.vogella.jvmmonitoring.memory;2import java.io.File;3import java.io.IOException;4import org.testng.TestNG;5import org.testng.TestRunner;6public class TestNGOutput {7    public static void main(String[] args) throws IOException {8        TestNG testNG = new TestNG();9        testNG.setOutputDirectory(System.getProperty("user.dir") + File.separator + "test-output");10        testNG.setTestClasses(new Class[] { TestClass.class });11        testNG.run();12        TestRunner testRunner = testNG.getTestRunner();13        String outputDirectory = testRunner.getOutputDirectory();14        System.out.println("TestNG output directory is: " + outputDirectory);15    }16}getOutputDirectory
Using AI Code Generation
1public void test() throws Exception {2    File outputDirectory = new TestRunner().getOutputDirectory();3    System.out.println(outputDirectory);4}5public void test() throws Exception {6    File outputDirectory = new TestRunner().getOutputDirectory();7    System.out.println(outputDirectory);8}getOutputDirectory
Using AI Code Generation
1import org.testng.TestRunner;2import org.apache.commons.io.FileUtils;3import java.io.File;4import java.io.IOException;5import java.util.Date;6import java.text.SimpleDateFormat;7import java.util.Calendar;8public class CopyTestOutput {9	public static void main(String[] args) {10		TestRunner runner = new TestRunner();11		String outputDir = runner.getOutputDirectory();12		System.out.println("Test Output Directory: " + outputDir);13		String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());14		String destDir = "C:\\Users\\srikanth\\Desktop\\TestNG\\TestNGReports\\TestNGReport" + timeStamp;15		File srcDir = new File(outputDir);16		File destDirFile = new File(destDir);17		try {18			FileUtils.copyDirectory(srcDir, destDirFile);19		} catch (IOException e) {20			e.printStackTrace();21		}22		System.out.println("Test Output Directory copied to: " + destDir);23	}24}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!!
