TestNG tests are executed automatically when we build a maven project. We can also run TestNG tests using Eclipse plugin. What if we don’t have the TestNG plugin installed for our IDE and we want to run some specific tests without doing a complete build. In this case, we can run TestNG test classes from a java main method too.
TestNG Test from Java Main Method
Let’s create a simple TestNG test class and a TestNG listener for our example.
1 2 3 4 5 6 7 8 9 10 |
package com.journaldev.main; import org.testng.annotations.Test; public class Test5 { @Test public void test() { System.out.println("Running test method"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.journaldev.main; import org.testng.ISuite; import org.testng.ISuiteListener; public class Test5SuiteListener implements ISuiteListener { @Override public void onStart(ISuite suite) { System.out.println("TestNG suite default output directory = "+suite.getOutputDirectory()); } @Override public void onFinish(ISuite suite) { System.out.println("TestNG invoked methods = " +suite.getAllInvokedMethods()); } } |
Now we want to run Test5
class tests and also want to add Test5SuiteListener
listener to our TestNG test suite. We can easily do this using org.testng.TestNG
class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.journaldev.main; import org.testng.TestNG; public class TestNGMainClass { public static void main(String[] args) { TestNG testSuite = new TestNG(); testSuite.setTestClasses(new Class[] { Test5.class }); testSuite.addListener(new Test5SuiteListener()); testSuite.setDefaultSuiteName("My Test Suite"); testSuite.setDefaultTestName("My Test"); testSuite.setOutputDirectory("/Users/pankaj/temp/testng-output"); testSuite.run(); } } |
Notice that I am also changing TestNG reporting output directory, setting the test suite and test name.
Just run above class as java application and it should produce following output in the console.
1 2 3 4 5 6 7 8 9 |
TestNG suite default output directory = /Users/pankaj/temp/testng-output/My Test Suite Running test method TestNG invoked methods = [Test5.test()[pri:0, instance:com.journaldev.main.Test5@314c508a] 827084938] =============================================== My Test Suite Total tests run: 1, Failures: 0, Skips: 0 =============================================== |
You should also check for the HTML report generated by above program, it will be something like below image.
That’s all for running TestNG tests from java main method.