简体   繁体   中英

Error when using the same string in different tests

I have the following scenario: I perform several tests (@Test) and tests in Cucumber, in Selenium Webdriver, Java.

The tests are going well. However , I want to leave a string stored in one @Test (public void) in another @Test (public void). I cannot.

Could anyone help?

First test:

@Test
public void testDocuments() {
     OneClass oneClass = new OneClass();
     oneClass.one();
     oneClass.two();
}

Second test:

@Test
public void testDocuments() {
     OneClass oneClass = new OneClass();
     oneClass.one();
     oneClass.two();
}

Method one

public String one() {
        if (this.cnpj == null) {
            this.cnpj = add.cnpj(false);
        } else {
        }
        return this.cnpj;
    }

Both tests I want you to use the same generated string !!!!

I look forward and thanks in advance!

I'm not sure what your method one() does, but assuming you want to use the same value for two different tests, why not just do this:

OneClass oneClass = new OneClass();
String yourGeneratedString = oneClass.one();  

// First test

@Test
public void testDocuments() {
     yourFunction(yourGeneratedString);
}

// Second test

@Test
public void testDocuments2() {
     yourOtherFunction(yourGeneratedString);
}

If I understand correctly, you need this.cnpj value to be available within the second test? Each time you do new OneClass() , it creates a new instance of it.

So you can do one of the following:

  • Use singleton instance of OneClass
  • Make cnpj a static field within OneClass

If I understand it right, you want to share data from one test to second one. If you user testNG then you can do it this way.

import org.testng.ITestContext;
import org.testng.annotations.Test;

public class MyTest {

  @Test
  public void testOne(ITestContext context){
    context.setAttribute("myKey", "myValue");
  }

  @Test
  public void testTwo(ITestContext context){
    String valueFromTestOne = (String) context.getAttribute("myKey");
    System.out.println("My key = " + valueFromTestOne);
  }
}

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM