Estevao FPM
Estevao FPM

Reputation: 111

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!

Upvotes: 1

Views: 102

Answers (3)

Motivated Mind
Motivated Mind

Reputation: 108

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);
  }
}

enter image description here

Upvotes: 1

Michael S
Michael S

Reputation: 104

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);
}

Upvotes: 3

Dima G
Dima G

Reputation: 2025

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

Upvotes: 2

Related Questions