添加依赖
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
</dependency>
创建Controller
@RestController
public class TestController {
@GetMapping("/run-tests")
public String runTests() throws IOException {
TestNG testng = new TestNG();
testng.setTestSuites(Collections.singletonList("src/main/resources/testng.xml"));
testng.run();
// 移动文件
moveTestOutputToStatic();
return "TestNG tests executed. Check the test-output directory for reports.";
}
private void moveTestOutputToStatic() throws IOException {
String projectPath = System.getProperty("user.dir");
Path sourceDir = Paths.get(projectPath + "/test-output");
Path targetDir = Paths.get(projectPath + "/target/classes/static/test-output");
if (!Files.exists(targetDir)) {
Files.createDirectories(targetDir);
}
Files.walk(sourceDir).forEach(sourcePath -> {
try {
Path targetPath = targetDir.resolve(sourceDir.relativize(sourcePath));
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
}
}
编写文件
<suite name="Test Suite" verbose="1">
<test name="Test Test">
<classes>
<class name="com.example.jvmdd.ExampleTest"/>
</classes>
</test>
</suite>
编写testcase
package com.example.jvmdd;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ExampleTest {
@Test
public void testMethod1() {
System.out.println("Test Method 1");
Assert.assertEquals(1,2);
}
@Test
public void testMethod2() {
System.out.println("Test Method 2");
}
}
操作步骤
http://localhost:8080/run-tests
报告查看
http://localhost:8080/test-output/index.html