下面列出了怎么用org.testng.TestNG的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) throws Exception {
int count = -1;
Stopwatch sw = Stopwatch.createStarted();
while (++count<100) {
log.info("new test run\n\n\nTEST RUN "+count+"\n");
// ElectPrimaryTest t = new ElectPrimaryTest();
// t.setUp();
// t.testFireCausesPromoteDemote();
// t.tearDown();
TestNG testNG = new TestNG();
testNG.setTestClasses(new Class[] { ElectPrimaryTest.class });
testNG.addListener((ITestNGListener)new LoggingVerboseReporter());
FailedReporter failedReporter = new FailedReporter();
testNG.addListener((ITestNGListener)failedReporter);
testNG.run();
if (!failedReporter.getFailedTests().isEmpty()) {
log.error("Failures: "+failedReporter.getFailedTests());
System.exit(1);
}
}
log.info("\n\nCompleted "+count+" runs in "+Duration.of(sw));
}
@Test
@Ignore("Fails against TestNG 6.11")
public void runTestAndAssertCounters() throws Exception {
TrackingTestNGTestListener listener = new TrackingTestNGTestListener();
TestNG testNG = new TestNG();
testNG.addListener((ITestNGListener) listener);
testNG.setTestClasses(new Class<?>[] {this.clazz});
testNG.setVerbose(0);
testNG.run();
String name = this.clazz.getSimpleName();
assertEquals("tests started for [" + name + "] ==> ", this.expectedTestStartCount, listener.testStartCount);
assertEquals("successful tests for [" + name + "] ==> ", this.expectedTestSuccessCount, listener.testSuccessCount);
assertEquals("failed tests for [" + name + "] ==> ", this.expectedFailureCount, listener.testFailureCount);
assertEquals("failed configurations for [" + name + "] ==> ",
this.expectedFailedConfigurationsCount, listener.failedConfigurationsCount);
}
/**
* Sets the test suite to run using the given URI reference. Three types of
* references are supported:
* <ul>
* <li>A file system reference</li>
* <li>A file: URI</li>
* <li>A jar: URI</li>
* </ul>
*
* @param driver
* The main TestNG driver.
* @param ets
* A URI referring to a suite definition.
*/
private void setTestSuites(TestNG driver, URI ets) {
if (ets.getScheme().equalsIgnoreCase("jar")) {
// jar:{url}!/{entry}
String[] jarPath = ets.getSchemeSpecificPart().split("!");
File jarFile = new File(URI.create(jarPath[0]));
driver.setTestJar(jarFile.getAbsolutePath());
driver.setXmlPathInJar(jarPath[1].substring(1));
} else {
List<String> testSuites = new ArrayList<String>();
File tngFile = new File(ets);
if (tngFile.exists()) {
LOGR.log(Level.CONFIG, "Using TestNG config file {0}", tngFile.getAbsolutePath());
testSuites.add(tngFile.getAbsolutePath());
} else {
throw new IllegalArgumentException("A valid TestNG config file reference is required.");
}
driver.setTestSuites(testSuites);
}
}
@SuppressWarnings("unchecked")
@AllureFeatures.Fixtures
@Issue("67")
@Test(description = "Should set correct status for failed after fixtures")
public void shouldSetCorrectStatusForFailedAfterFixtures() {
final Consumer<TestNG> configurer = parallel(XmlSuite.ParallelMode.METHODS, 5);
final AllureResults results = runTestNgSuites(
configurer,
"suites/failed-after-suite-fixture.xml",
"suites/failed-after-test-fixture.xml",
"suites/failed-after-method-fixture.xml"
);
assertThat(results.getTestResultContainers())
.flatExtracting(TestResultContainer::getAfters)
.hasSize(3)
.extracting(FixtureResult::getName, FixtureResult::getStatus)
.containsExactlyInAnyOrder(
Tuple.tuple("afterSuite", Status.BROKEN),
Tuple.tuple("afterTest", Status.BROKEN),
Tuple.tuple("afterMethod", Status.BROKEN)
);
}
@Override
public void run() throws Throwable {
for (String className : testClassNames) {
Class<?> testClass = Class.forName(className);
List<TestResult> results;
if (!mightBeATestClass(testClass)) {
results = Collections.emptyList();
} else {
results = new ArrayList<>();
TestNG testng = new TestNG();
testng.setUseDefaultListeners(false);
testng.addListener(new FilteringAnnotationTransformer(results));
testng.setTestClasses(new Class<?>[] {testClass});
testng.addListener(new TestListener(results));
// use default TestNG reporters ...
testng.addListener(new SuiteHTMLReporter());
testng.addListener((IReporter) new FailedReporter());
testng.addListener(new XMLReporter());
testng.addListener(new EmailableReporter());
// ... except this replaces JUnitReportReporter ...
testng.addListener(new JUnitReportReporterWithMethodParameters());
// ... and we can't access TestNG verbosity, so we remove VerboseReporter
testng.run();
}
writeResult(className, results);
}
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {ReflectionFactoryTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {ReflectionFactoryTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
public static void main(String[] args) {
ITestNGListener tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[] { CatalogYamlTemplateTest.class });
testng.addListener(tla);
testng.run();
}
@SuppressWarnings("deprecation")
private TestNG getTestNG() {
try {
return TestNG.getDefault();
} catch (Exception e) {
try {
Field field = ClassUtil.getField("m_instance", TestNG.class);
field.setAccessible(true);
return (TestNG) field.get(null);
} catch (Throwable e1) {
}
}
return null;
}
protected void runTest( String outputFolder, Class theTest, SuiteContainer sC )
{
int threadCount = Integer.parseInt( System.getProperty( "xF-ThreadCount", "10" ) );
int verboseLevel = Integer.parseInt( System.getProperty( "xF-VerboseLevel", "10" ) );
TestNG testNg = new TestNG( true );
testNg.setVerbose( verboseLevel );
testNg.setThreadCount( threadCount );
testNg.setDataProviderThreadCount( threadCount );
testNg.setOutputDirectory( outputFolder + System.getProperty( "file.separator" ) + "testNg" );
testNg.setTestClasses( new Class[] { theTest } );
testNg.run();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TestNG test = new TestNG();
test.setTestClasses(new Class[]{DAWGNodeTest.class, DAWGTest.class});
test.run();
}
@BeforeClass
public static void setUp() throws IOException {
resultsDir = Files.createTempDirectory(ALLURE_RESULTS);
AllureResultsUtils.setResultsDirectory(resultsDir.toFile());
List<XmlSuite> suites = new ArrayList<>();
for (ConfigMethodType type : ConfigMethodType.values()) {
suites.add(createSuite(type.getTitle()));
}
TestNG testNG = new TestNG();
testNG.setXmlSuites(suites);
testNG.setUseDefaultListeners(false);
testNG.run();
}
public static Response debugAction(Class clazz) {
TestNG testNG = run(new Class[]{clazz}, Arrays.asList(DebugActionTestListener.class));
if (testNG.getStatus() != 0) { // 运行有错误
return Response.fail(DebugActionTestListener.getFailMsg());
} else { // 运行成功
List<String> printMsgList = DebugActionTestListener.getPrintMsgList();
if (CollectionUtils.isEmpty(printMsgList)) {
printMsgList = Arrays.asList("执行成功");
}
return Response.success(printMsgList.stream().collect(Collectors.joining("\n")));
}
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {ReflectionFactoryTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
@Test
public void report_failure_on_incorrect_stubbing_syntax_with_matchers_in_test_methods() throws Exception {
TestNG testNG = new_TestNG_with_failure_recorder_for(FailingOnPurposeBecauseIncorrectStubbingSyntax.class);
testNG.run();
assertTrue(testNG.hasFailure());
assertThat(failureRecorder.lastThrowable()).isInstanceOf(InvalidUseOfMatchersException.class);
}
@Test
public void report_failure_on_incorrect_stubbing_syntax_with_matchers_in_configuration_methods() throws Exception {
TestNG testNG = new_TestNG_with_failure_recorder_for(FailingOnPurposeBecauseWrongStubbingSyntaxInConfigurationMethod.class);
testNG.run();
assertTrue(testNG.hasFailure());
assertThat(failureRecorder.lastThrowable()).isInstanceOf(InvalidUseOfMatchersException.class);
}
/**
* Runs the existing webapp test cases, this time against the initiated secure server instance.
* @throws Exception
*/
@Test
public void runOtherSuitesAgainstSecureServer() throws Exception {
final PropertiesConfiguration configuration = new PropertiesConfiguration();
configuration.setProperty(CERT_STORES_CREDENTIAL_PROVIDER_PATH, providerUrl);
// setup the credential provider
setupCredentials();
try {
secureEmbeddedServer = new SecureEmbeddedServer(
EmbeddedServer.ATLAS_DEFAULT_BIND_ADDRESS, securePort, TestUtils.getWarPath()) {
@Override
protected PropertiesConfiguration getConfiguration() {
return configuration;
}
};
secureEmbeddedServer.server.start();
TestListenerAdapter tla = new TestListenerAdapter();
TestNG testng = new TestNG();
testng.setTestClasses(new Class[]{AdminJerseyResourceIT.class, EntityJerseyResourceIT.class,
TypesJerseyResourceIT.class});
testng.addListener(tla);
testng.run();
} finally {
secureEmbeddedServer.server.stop();
}
}
public void report_failure_on_incorrect_annotation_usage() throws Throwable {
TestNG testNG = new_TestNG_with_failure_recorder_for(FailingOnPurposeBecauseIncorrectAnnotationUsage.class);
testNG.run();
assertTrue(testNG.hasFailure());
assertThat(failureRecorder.lastThrowable()).isInstanceOf(MockitoException.class);
}
@Override
public void execute(String jarFilePath, DeploymentCreationResult deploymentCreationResult) {
File jarFile = new File(jarFilePath);
String jarName = jarFile.getName().substring(0, jarFile.getName().lastIndexOf("."));
loadJarToClasspath(jarFile);
TestNG testng = new TestNG();
testng.setTestJar(jarFilePath);
testng.setOutputDirectory(Paths.get(testsLocation, "Results", "TestNG" + jarName).toString());
testng.run();
}
@SuppressWarnings("raw_types")
public static void main(String[] args) {
Class<?>[] testclass = { OnExitTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
@SuppressWarnings("raw_types")
public static void main(String[] args) {
Class<?>[] testclass = {InfoTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
/**
* @param args
*/
public static void main(String[] args) {
BasicConfigurator.configure();
Logger.getRootLogger().setLevel(Level.INFO);
TestNG testng = new TestNG();
List<String> suites = new ArrayList<String>();
suites.add("src/test/resources/testng.xml");
testng.setTestSuites(suites);
testng.setOutputDirectory("target/test-output");
testng.run();
}
@SuppressWarnings("raw_types")
public static void main(String[] args) {
Class<?>[] testclass = {TreeTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {SunMiscSignalTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {ReflectionFactoryTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {ObjectStreamTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
public TestngRun() {
tng=new TestNG();
listener=new TestListenerAdapter();//定义监听器类型
tng.addListener(listener);
xmlFileList=new ArrayList<>();//记录测试使用的xml文件路径列表
testReport=new TestReport();//记录测试报告测试报告信息
runInfo=new TestRunInfo();
}
@SuppressWarnings("raw_types")
@Test(enabled = false)
public static void main(String[] args) {
Class<?>[] testclass = {ReflectionFactoryTest.class};
TestNG testng = new TestNG();
testng.setTestClasses(testclass);
testng.run();
}
public boolean runMethodParallel() {
TestNG testNG = new TestNG();
List<String> suites = Lists.newArrayList();
suites.add(getProperty("user.dir") + PARALLEL_XML_LOCATION);
testNG.setTestSuites(suites);
testNG.run();
return testNG.hasFailure();
}
public static void main(final String[] args) {
TestNG.main(args);
}