testng

偏执的太偏执、 2023-10-09 12:48 50阅读 0赞

结构

1623038-20190807010424294-746851816.png

common

ExcelTool

  1. package com.sa.testng.common;
  2. import com.sa.testng.test.TestConfig;
  3. import org.apache.poi.ss.usermodel.Cell;
  4. import org.apache.poi.xssf.usermodel.XSSFSheet;
  5. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Component;
  8. import java.io.FileInputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. /**
  12. * 描述:excel事件处理
  13. *
  14. * @author Keyba
  15. */
  16. @Component
  17. public class ExcelTool {
  18. /**
  19. * 读取excel文件中的数据,并生成数组
  20. */
  21. private final TestConfig testConfig;
  22. @Autowired
  23. public ExcelTool(TestConfig testConfig) {
  24. this.testConfig = testConfig;
  25. }
  26. /**
  27. * @SuppressWarnings("deprecation")
  28. */
  29. public Object[][] readExcel(String sheetName) throws IOException {
  30. // 读数据
  31. InputStream fileInputStream = new FileInputStream(testConfig.getFilePath());
  32. XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
  33. //读取指定标签页的数据
  34. XSSFSheet sheet = workbook.getSheet(sheetName);
  35. //获取行数(获取的是物理行数,也就是不包括那些空行(隔行)的情况)
  36. int rowNum = sheet.getPhysicalNumberOfRows();
  37. //获取列数
  38. int columnNum = sheet.getRow(0).getPhysicalNumberOfCells();
  39. //因为第一行作为字段名,不需要记录,所以只有[rowNum-1]行
  40. Object[][] data = new Object[rowNum - 1][columnNum];
  41. for (int i = 1; i < rowNum; i++) {
  42. for (int h = 0; h < columnNum; h++) {
  43. //先把类型设置为string
  44. sheet.getRow(i).getCell(h).setCellType(Cell.CELL_TYPE_STRING);
  45. //填充数组
  46. data[i - 1][h] = sheet.getRow(i).getCell(h).getStringCellValue();
  47. }
  48. }
  49. workbook.close();
  50. return data;
  51. }
  52. }

ScreenShotOnFailure

  1. package com.sa.testng.common;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Paths;
  5. import org.apache.commons.io.FileUtils;
  6. import org.openqa.selenium.OutputType;
  7. import org.openqa.selenium.TakesScreenshot;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Component;
  10. @Component
  11. class ScreenShotOnFailure {
  12. private final static String SCREEN_SHOT_PATH = "test-output/screen-shot";
  13. private static String SCREEN_SHOT_NAME = null;
  14. private static TestWebDriver testWebDriver;
  15. @Autowired
  16. public ScreenShotOnFailure(TestWebDriver testWebDriver) {
  17. ScreenShotOnFailure.testWebDriver = testWebDriver;
  18. }
  19. static void takeScreenShot() throws IOException {
  20. File screenShotDir = new File(SCREEN_SHOT_PATH);
  21. if (!screenShotDir.exists()) {
  22. screenShotDir.mkdirs();
  23. }
  24. SCREEN_SHOT_NAME = System.currentTimeMillis() + ".jpg";
  25. File screenFile = ((TakesScreenshot) testWebDriver.getWebDriver()).getScreenshotAs(OutputType.FILE);
  26. File savedFile = new File(Paths.get(SCREEN_SHOT_PATH, SCREEN_SHOT_NAME).toString());
  27. FileUtils.copyFile(screenFile, savedFile);
  28. testWebDriver.stopWebDrover();
  29. }
  30. static String getScreenShotPath() {
  31. return SCREEN_SHOT_PATH;
  32. }
  33. static String getScreenShotName() {
  34. return SCREEN_SHOT_NAME;
  35. }
  36. }

TestNGRetryListener

  1. package com.sa.testng.common;
  2. import org.springframework.stereotype.Component;
  3. import org.testng.ITestContext;
  4. import org.testng.ITestListener;
  5. import org.testng.ITestResult;
  6. import java.io.IOException;
  7. /**
  8. * @author Keyba
  9. */
  10. @Component
  11. public class TestNGRetryListener implements ITestListener {
  12. @Override
  13. public void onTestFailure(ITestResult result) {
  14. try {
  15. ScreenShotOnFailure.takeScreenShot();
  16. System.out.println(result.getMethod().getMethodName() + " failed, the screenshot saved in "
  17. + ScreenShotOnFailure.getScreenShotPath() + " screenshot name : "
  18. + ScreenShotOnFailure.getScreenShotName());
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. @Override
  24. public void onTestStart(ITestResult result) {
  25. // TODO Auto-generated method stub
  26. }
  27. @Override
  28. public void onTestSuccess(ITestResult result) {
  29. // TODO Auto-generated method stub
  30. }
  31. @Override
  32. public void onTestSkipped(ITestResult result) {
  33. // TODO Auto-generated method stub
  34. }
  35. @Override
  36. public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
  37. // TODO Auto-generated method stub
  38. }
  39. @Override
  40. public void onFinish(ITestContext iTestContext) {
  41. }
  42. @Override
  43. public void onStart(ITestContext context) {
  44. // TODO Auto-generated method stub
  45. }
  46. }

TestWebDriver

  1. package com.sa.testng.common;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * @author Keyba
  7. */
  8. @Component
  9. public class TestWebDriver {
  10. private static WebDriver driver;
  11. TestWebDriver() {
  12. }
  13. public WebDriver getWebDriver() {
  14. System.setProperty("webdriver.chrome.driver", "D:\\dl\\chromedriver.exe");
  15. driver = new ChromeDriver();
  16. driver.manage().window().maximize();
  17. driver.navigate().to("http://www.baidu.com");
  18. return driver;
  19. }
  20. void stopWebDrover() {
  21. driver.quit();
  22. }
  23. }

config

  1. package com.sa.testng.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. /**
  5. * @author Keyba
  6. */
  7. @Configuration
  8. @ConfigurationProperties(prefix = "url")
  9. public class UrlConfig {
  10. private String loginUrl;
  11. public String getLoginUrl() {
  12. return loginUrl;
  13. }
  14. }

action

BaseAction

  1. package com.sa.testng.config;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. /**
  5. * @author Keyba
  6. */
  7. @Configuration
  8. @ConfigurationProperties(prefix = "url")
  9. public class UrlConfig {
  10. private String loginUrl;
  11. public String getLoginUrl() {
  12. return loginUrl;
  13. }
  14. }

LoginPageAction

  1. package com.sa.testng.libarary.action;
  2. import com.sa.testng.libarary.base.mall.MallType;
  3. import com.sa.testng.libarary.base.user.User;
  4. import com.sa.testng.libarary.page.login.LoginPage;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. /**
  8. * @author Keyba
  9. */
  10. @Service
  11. public class LoginPageAction extends BaseAction {
  12. private final LoginPage loginPage;
  13. @Autowired
  14. public LoginPageAction(LoginPage loginPage) {
  15. this.loginPage = loginPage;
  16. }
  17. public void login(User user, MallType mallType) throws Exception {
  18. loginPage.chooseMall(mallType);
  19. loginPage.inputUser(user.getName());
  20. loginPage.inputPassword(user.getPassword());
  21. loginPage.inputCaptcha("888888");
  22. loginPage.clickLoginButton();
  23. }
  24. }

page

LoginPage

  1. package com.sa.testng.libarary.page.login;
  2. import com.sa.testng.config.UrlConfig;
  3. import com.sa.testng.libarary.base.mall.MallType;
  4. import com.sa.testng.libarary.page.BasePage;
  5. import org.openqa.selenium.WebElement;
  6. import org.openqa.selenium.support.CacheLookup;
  7. import org.openqa.selenium.support.FindBy;
  8. import org.openqa.selenium.support.PageFactory;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Repository;
  11. /**
  12. * @author Keyba
  13. */
  14. @Repository
  15. public class LoginPage extends BasePage {
  16. private final
  17. UrlConfig urlConfig;
  18. @Autowired
  19. LoginPage(UrlConfig urlConfig) {
  20. super();
  21. this.urlConfig = urlConfig;
  22. PageFactory.initElements(driver, this);
  23. driver.navigate().to(this.urlConfig.getLoginUrl());
  24. }
  25. @FindBy(xpath = "//div[@class=\"el-radio-group\"]/label[1]")
  26. @CacheLookup
  27. private WebElement productMallRadio;
  28. @FindBy(xpath = "//div[@class=\"el-radio-group\"]/label[2]")
  29. @CacheLookup
  30. private
  31. WebElement materivalMallRadio;
  32. @FindBy(xpath = "//div[@class=\"el-radio-group\"]/label[3]")
  33. @CacheLookup
  34. private
  35. WebElement thirdPartyRadio;
  36. @FindBy(xpath = "//*[@id=\"app\"]/div/main/div/div[2]/div[5]/div/div/div[2]/input")
  37. @CacheLookup
  38. private
  39. WebElement userName;
  40. @FindBy(xpath = "//div[@class=\"password\"]/input")
  41. @CacheLookup
  42. private
  43. WebElement password;
  44. @FindBy(xpath = "//input[@class=\"digital-patchca-input\"]")
  45. @CacheLookup
  46. private
  47. WebElement captcha;
  48. @FindBy(linkText = "登录")
  49. @CacheLookup
  50. private
  51. WebElement loginButton;
  52. public void chooseMall(MallType mallType) throws Exception {
  53. switch (mallType) {
  54. case ThreeParties:
  55. thirdPartyRadio.click();
  56. break;
  57. case Material:
  58. materivalMallRadio.click();
  59. break;
  60. case Product:
  61. productMallRadio.click();
  62. break;
  63. default:
  64. throw new Exception("商城类型错误");
  65. }
  66. }
  67. public void inputUser(String userName) {
  68. this.userName.sendKeys(userName);
  69. }
  70. public void inputPassword(String password) {
  71. this.password.sendKeys(password);
  72. }
  73. public void inputCaptcha(String captcha) {
  74. this.captcha.sendKeys(captcha);
  75. }
  76. public void clickLoginButton() {
  77. this.loginButton.click();
  78. }
  79. }

BasePage

  1. package com.sa.testng.libarary.page;
  2. import org.openqa.selenium.WebDriver;
  3. import org.openqa.selenium.chrome.ChromeDriver;
  4. import org.springframework.stereotype.Repository;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * @author Keyba
  8. */
  9. @Repository
  10. public class BasePage {
  11. public WebDriver driver;
  12. public BasePage() {
  13. System.setProperty("webdriver.chrome.driver", "E:\\CODE\\SaTestNG\\src\\main\\java\\com\\sa\\testng\\libarary\\tools\\chromedriver.exe");
  14. driver = new ChromeDriver();
  15. driver.manage().window().maximize();
  16. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  17. driver.manage().deleteAllCookies();
  18. }
  19. }

test

TestConfig

  1. package com.sa.testng.test;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Configuration;
  4. /**
  5. * @author Keyba
  6. */
  7. @Configuration
  8. @ConfigurationProperties(prefix = "app")
  9. public class TestConfig {
  10. public int getConfig() {
  11. return config;
  12. }
  13. public void setConfig(int config) {
  14. this.config = config;
  15. }
  16. public String getFilePath() {
  17. return filePath;
  18. }
  19. public void setFilePath(String filePath) {
  20. this.filePath = filePath;
  21. }
  22. private int config;
  23. private String filePath;
  24. }

TestService

  1. package com.sa.testng.test;
  2. /**
  3. * @author Keyba
  4. */
  5. public interface TestService {
  6. /**
  7. * invokeService
  8. * @return int
  9. */
  10. int invokeService();
  11. }

TestServieImpl

  1. package com.sa.testng.test;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Service;
  4. @Service
  5. public class TestServiceImpl implements TestService {
  6. private final TestConfig testConfig;
  7. @Autowired
  8. public TestServiceImpl(TestConfig testConfig) {
  9. this.testConfig = testConfig;
  10. }
  11. @Override
  12. public int invokeService() {
  13. System.out.println("invokeService");
  14. return testConfig.getConfig();
  15. }
  16. }

Appication

  1. package com.sa;
  2. import com.sa.testng.test.TestConfig;
  3. import com.sa.testng.config.UrlConfig;
  4. import org.springframework.boot.SpringApplication;
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;
  6. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  7. @SpringBootApplication
  8. @EnableConfigurationProperties({UrlConfig.class, TestConfig.class})
  9. public class Application {
  10. public static void main(String[] args) {
  11. // 程序启动入口
  12. // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
  13. SpringApplication.run(Application.class, args);
  14. }
  15. }

application.properties

  1. app.config=1
  2. excelFile=E:\\CODE\\JAVA\\SaTestNGProj\\src\\main\\resources\\test01.xlsx

test

testng.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
  3. <suite name="Default suite">
  4. <listeners>
  5. <listener class-name="com.sa.testng.common.TestNGRetryListener"/>
  6. </listeners>
  7. <test verbose="2" name="Default test">
  8. <groups>
  9. <define name="testGroup01">
  10. <include name="P1"/>
  11. <include name="P2"/>
  12. </define>
  13. <run>
  14. <include name="testGroup01"/>
  15. </run>
  16. </groups>
  17. <classes>
  18. <class name="com.sa.testng.TestServiceTest"/>
  19. </classes>
  20. </test> <!-- Default test -->
  21. </suite> <!-- Default suite -->

TestServiceTest

  1. package com.sa.testng;
  2. import com.sa.Application;
  3. import com.sa.testng.common.ExcelTool;
  4. import com.sa.testng.libarary.action.LoginPageAction;
  5. import com.sa.testng.libarary.base.mall.MallType;
  6. import com.sa.testng.libarary.base.user.Supplier;
  7. import com.sa.testng.libarary.base.user.User;
  8. import com.sa.testng.test.TestService;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.boot.test.context.SpringBootTest;
  11. import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
  12. import org.testng.Assert;
  13. import org.testng.annotations.*;
  14. import java.io.IOException;
  15. @SpringBootTest(classes = {Application.class})
  16. public class TestServiceTest extends AbstractTestNGSpringContextTests {
  17. @Autowired
  18. private TestService testServiceImpl;
  19. @Autowired
  20. private ExcelTool excelTool;
  21. @Autowired
  22. private LoginPageAction loginPageAction;
  23. @Autowired
  24. private User user;
  25. @Autowired
  26. private Supplier supplier;
  27. @DataProvider(name = "testExcelData")
  28. public Object[][] getExcelData() throws IOException {
  29. return excelTool.readExcel("Sheet1");
  30. }
  31. @Test(groups = "P1", description = "登录商城", dataProvider = "testExcelData")
  32. public void testLoginProductMall() throws Exception {
  33. supplier.setName("admin");
  34. supplier.setPassword("password");
  35. loginPageAction.login(supplier, MallType.Product);
  36. }
  37. @Test(groups = "TestP1", description = "用户登录", dataProvider = "testExcelData")
  38. public void test1(String result, String param1, String param2) {
  39. System.out.println(String.join(",", result, param1, param2));
  40. Assert.assertEquals(testServiceImpl.invokeService(), 2);
  41. }
  42. @Test(groups = "TestP1")
  43. public void test2() {
  44. Assert.assertEquals(testServiceImpl.invokeService(), 3);
  45. }
  46. @Test(groups = "TestP1")
  47. public void test3() {
  48. System.out.println("in test3");
  49. }
  50. }

TestServiceTest01.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
  3. <suite name="Suite1" parallel="classes" thread-count="1">
  4. <test verbose="1" name="test">
  5. <groups>
  6. <define name="testGroup01">
  7. <include name="P1"/>
  8. </define>
  9. <run>
  10. <include name="testGroup01"/>
  11. </run>
  12. </groups>
  13. <classes>
  14. <!-- 可以多个 -->
  15. <class name="com.sa.testng.TestServiceTest"/>
  16. </classes>
  17. </test>
  18. </suite>

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.sa</groupId>
  7. <artifactId>testNG</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <packaging>jar</packaging>
  10. <name>SaTestNGProj</name>
  11. <description>Use TestNG for sa test</description>
  12. <parent>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-parent</artifactId>
  15. <version>2.0.3.RELEASE</version>
  16. <relativePath/> <!-- lookup parent from repository -->
  17. </parent>
  18. <properties>
  19. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  20. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  21. <java.version>1.8</java.version>
  22. </properties>
  23. <dependencies>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-configuration-processor</artifactId>
  31. <optional>true</optional>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-test</artifactId>
  36. <scope>test</scope>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.testng</groupId>
  40. <artifactId>testng</artifactId>
  41. <version>6.9.10</version>
  42. </dependency>
  43. <!-- 依赖reportNg 关联testNg -->
  44. <dependency>
  45. <groupId>org.uncommons</groupId>
  46. <artifactId>reportng</artifactId>
  47. <version>1.1.4</version>
  48. <scope>test</scope>
  49. <exclusions>
  50. <exclusion>
  51. <groupId>org.testng</groupId>
  52. <artifactId>testng</artifactId>
  53. </exclusion>
  54. </exclusions>
  55. </dependency>
  56. <!-- 依赖Guice -->
  57. <dependency>
  58. <groupId>com.google.inject</groupId>
  59. <artifactId>guice</artifactId>
  60. <version>3.0</version>
  61. <scope>test</scope>
  62. </dependency>
  63. <dependency>
  64. <groupId>org.seleniumhq.selenium</groupId>
  65. <artifactId>selenium-java</artifactId>
  66. <version>2.52.0</version>
  67. <scope>compile</scope>
  68. <!--
  69. scope标签中对应值的解释:
  70. * compile,缺省值,适用于所有阶段,会随着项目一起发布。
  71. * provided,类似 compile,期望 JDK、容器或使用者会提供这个依赖。如 servlet.jar。
  72. * runtime,只在运行时使用,如 JDBC 驱动,适用运行和测试阶段。
  73. * test,只在测试时使用,用于编译和运行测试代码。不会随项目发布。
  74. * system,类似 provided,需要显式提供包含依赖的 jar, Maven 不会在 Repository 中查找它。
  75. -->
  76. </dependency>
  77. <!-- ***************************** poi ***************************** -->
  78. <!-- poi HSSF is our port of the Microsoft Excel 97(-2007) file format (BIFF8) to pure Java. -->
  79. <dependency>
  80. <groupId>org.apache.poi</groupId>
  81. <artifactId>poi</artifactId>
  82. <version>3.14</version>
  83. </dependency>
  84. <!-- poi-ooxml XSSF is our port of the Microsoft Excel XML (2007+) file format (OOXML) to pure Java -->
  85. <dependency>
  86. <groupId>org.apache.poi</groupId>
  87. <artifactId>poi-ooxml</artifactId>
  88. <version>3.14</version>
  89. </dependency>
  90. <dependency>
  91. <groupId>org.apache.poi</groupId>
  92. <artifactId>poi-ooxml-schemas</artifactId>
  93. <version>3.14</version>
  94. </dependency>
  95. </dependencies>
  96. <build>
  97. <plugins>
  98. <plugin>
  99. <groupId>org.springframework.boot</groupId>
  100. <artifactId>spring-boot-maven-plugin</artifactId>
  101. </plugin>
  102. <!-- 添加插件 关联testNg.xml -->
  103. <plugin>
  104. <groupId>org.apache.maven.plugins</groupId>
  105. <artifactId>maven-surefire-plugin</artifactId>
  106. <version>2.5</version>
  107. <configuration>
  108. <suiteXmlFiles>
  109. <suiteXmlFile>src/test/java/com/sa/testng/testng.xml</suiteXmlFile>
  110. </suiteXmlFiles>
  111. <properties>
  112. <property>
  113. <name>usedefaultlisteners</name>
  114. <value>false</value>
  115. </property>
  116. <property>
  117. <name>listener</name>
  118. <value>org.uncommons.reportng.HTMLReporter</value>
  119. </property>
  120. </properties>
  121. </configuration>
  122. </plugin>
  123. </plugins>
  124. </build>
  125. </project>

转载于:https://www.cnblogs.com/liehen2046/p/11312803.html

发表评论

表情:
评论列表 (有 0 条评论,50人围观)

还没有评论,来说两句吧...

相关阅读

    相关 TestNG

    经常在使用TestNG的注解时,忘记这些差异不大的注解的执行顺序;或者忘记用什么注解。所以这里归纳总结一下。 注解 说明 @BeforeSuite The annotat

    相关 TestNG注解

    注解 描述 @BeforeSuite 在该套件的所有测试都运行在注释的方法之前,仅运行一次 @AfterSuite 在该套件的所有测试都运行在注释方法之后,仅运行一次 @...