【问题标题】:How to pass a variable from BeforeTest to Test annotation如何将变量从 BeforeTest 传递到 Test 注释
【发布时间】:2015-12-15 15:23:47
【问题描述】:

我正在尝试在@BeforeTest 方法中从excel 中读取数据,并尝试在testNG 中的@Test 方法中打印相同的数据。我已经阅读了工作表中的数据

@BeforeTest
    @Parameters({"filePath", "fileName", "sheetName"})
    public void readExcel(String filePath, String fileName, String sheetName) throws IOException, EncryptedDocumentException, InvalidFormatException{
        // set the file path
        File eFile = new File(filePath+"\\"+fileName);
        //print the file path
        System.out.println("File is at: "+eFile);

        FileInputStream inputstream = new FileInputStream(eFile);

        // Read and publish extension
        String extensionName = fileName.substring(fileName.indexOf("."));
        System.out.println("File type is: "+extensionName);

        //Read the file
        Workbook wb = new XSSFWorkbook(inputstream);

        //Read the sheet name
        Sheet wbSheet = wb.getSheet(sheetName);

    }

我想将 wbSheet 传递给 @Test 方法以打印数据并将数据写入 excel。 @Parameters 正在寻找在 testng.xml 中定义的常量。如何传递这样的变量..?

【问题讨论】:

  • 对象变量,即测试类中的字段呢?

标签: java annotations testng


【解决方案1】:

为什么不使用实例变量?

class YourClassTest {

  Sheet wbSheet;

  @BeforeTest public void readExcel(...) {
    wbSheet = wb.getSheet(sheetName);
  }

  @Test public void test() {
    //you can use wbSheet here
  }

}

【讨论】:

    【解决方案2】:

    我猜在@BeforeTest 中定义和定义的任何变量都可以在@Test 中使用。 如果我错了,请纠正我。 下面的例子对我有用:

    @BeforeTest
    public void getUrl(){
    
        RestAssured.baseURI = envProp.getProperty("HOST_GET");
    
    }
    
    @Test
    public void listUsers() {
    
    given().when().get("/maps/...").then().assertThat().statusCode(200);
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2011-04-02
      • 2016-02-16
      • 2010-11-02
      相关资源
      最近更新 更多