如何在Test方法中使用BeforeMethod输出

时间:2016-05-31 15:35:46

标签: java selenium selenium-webdriver testng

我的@BeforeMethod会生成一个输出。

@BeforeMethod
public  void Random() throws Exception {
    //Generating Random Text
    int leftLimit = 97; 
    int rightLimit = 122; 
    int targetStringLength = 3;
    StringBuilder buffer = new StringBuilder(targetStringLength);
    for (int i = 0; i < targetStringLength; i++) {
        int randomLimitedInt = leftLimit + (int) 
          (new Random().nextFloat() * (rightLimit - leftLimit));
        buffer.append((char) randomLimitedInt);
    }
    String generatedString = buffer.toString();

    System.out.println(generatedString);


}

如何在下面的方法

中使用@BeforeMethod的输出
@Test(priority = 1)
    public  void Registration() throws Exception {

        driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/UIATableCell[2]/UIATextField[1]")).sendKeys("abc" + generatedString);
}

1 个答案:

答案 0 :(得分:1)

您的问题的解决方案是将生成的字符串存储在类级别变量(字段)中。例如,在课程级别对private String generatedString进行评分,并在之前的方法中设置generatedString

但是,因为你在before方法中所做的只是生成一个随机字符串,所以让你的随机生成方法只是一个可以从类中的任何位置调用的常规方法更有意义。

@Test(priority = 1)
public void registration() throws Exception {
    String randomString = generateRandomString();
    driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/UIATableCell[2]/UIATextField[1]")).sendKeys("abc" + randomString);
}

public String generateRandomString() throws Exception {
    //Generating Random Text
    int leftLimit = 97; 
    int rightLimit = 122; 
    int targetStringLength = 3;
    StringBuilder buffer = new StringBuilder(targetStringLength);
    for (int i = 0; i < targetStringLength; i++) {
        int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
        buffer.append((char) randomLimitedInt);
    }
    String generatedString = buffer.toString();

    System.out.println(generatedString);

    return generatedString;
}

我还应该提到,有许多好的库都有解决方案来生成随机字符串。 Apache的RandomStringUtils类就是一个例子。

编辑:针对以下仅生成一个随机字符串的问题:

private final static String RANDOM_STRING = generateRandomString();

@Test(priority = 1)
public void registration() throws Exception {
    driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIATableView[1]/UIATableCell[2]/UIATextField[1]")).sendKeys("abc" + RANDOM_STRING);
}

public String generateRandomString() throws Exception {
    //Generating Random Text
    int leftLimit = 97; 
    int rightLimit = 122; 
    int targetStringLength = 3;
    StringBuilder buffer = new StringBuilder(targetStringLength);
    for (int i = 0; i < targetStringLength; i++) {
        int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit));
        buffer.append((char) randomLimitedInt);
    }
    String generatedString = buffer.toString();

    System.out.println(generatedString);

    return generatedString;
}