Skip to content
Advertisement

Error calling method using same data (new data is always generated)

I have the following problem to be solved, could you help me?

I have two methods in a class. The first generates a document (calling another class) and stores it in a string.

The second one I want to save this document number for use in other methods and in other classes, in a way that the document is the same generated initially. That is, do not generate a different document! I’m not getting … = //

First Methods in one class (generates document, calling a method of another class):

public class oneClass {
private String cpf;
private String document() {
        if (this.cpf == null) {
            this.cpf = incluiDocumento.cpf(false);
        } else {
        }
        return this.cpf;
    }

    public void one() {
        System.out.println(document());
        System.out.println(document());
        System.out.println(document());
    }

    public void two() {
        System.out.println(document());
    }
}

Second class:

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

Conclusion: I can generate my document and store it in a string. However, in the next methods and classes, I can never use the first document ever generated. It will always generate new documents.

How can I generate a document and store it for use in tests and validate it?

Tool: Selenium Webdriver, Java.

Thanks in advance!!!

Advertisement

Answer

In this case you might use this approach:

public class OneClass{    
    private String cpf;
    //...
    public String document() {
        if(this.cpf==null){
            this.cpf = document.cpf(false);
        }
        return this.cpf; 
    }
    //... method one() and two()
}

The document is created only once and saved in a class variable. Any call after that will return the saved document.

So the Second Method will always get the first document generated.

Edit:

And test it like in the following:

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

I changed the name of your class from oneClass to OneClass because in Java class names start with capital letter.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement