EvoSuite / evosuite

EvoSuite - automated generation of JUnit test suites for Java classes
http://www.evosuite.org
GNU Lesser General Public License v3.0
832 stars 341 forks source link

How to generate testcases for main() method with system.out.println() statements #370

Closed ssk1216 closed 3 years ago

ssk1216 commented 3 years ago

Context

Please provide below a detailed introduction to the issue itself, and describe what you were doing when the issue happened. Or, what do you want to achieve?

public class Area {

public static void main(String[] args) {
    float a, b, a1, b1;
    float area;

    Scanner obj=new Scanner(System.in);

    a = obj.nextFloat();
    b = obj.nextFloat();

    a1 = a;
    b1 = b;
    if(a < 0) {
        a1 = -a;
    }
    if(b < 0) {
        b1 = -b;
    }

    area = (float)(0.5 * a1 * b1);

    System.out.printf("The area of (%.4f,%.4f), (%.4f,0) and (0,%.4f) is %.4f.\n", a, b, a, b, area);
}

}

------------------- The above program is to calculate the area of a triangle---------------------- , When Evosuite was used to generate testcase for this program

One of the test which was generated is as follows.

@Test(timeout = 4000) public void test0() throws Throwable { SystemInUtil.addInputLine("-2");
SystemInUtil.addInputLine("8"); Area.main((String[]) null); }

What I infer from the above code is SystemInUtil.addInputLine("-2"); - passes a value -2 for the variable a, followed by 8 for variable b. What is the purpose of (String[] null)?

How can we test programs where we have a system.out.print() as the above programs????

Any suggestions will be much appreciated

gofraser commented 3 years ago

The function main requires an input of type String[], and EvoSuite will always cast null values to prevent compilation errors (which may arise in many different scenarios if one doesn't do this in automatically generated code).

I am not sure what exactly you are asking, are you asking how to add assertions that check the output on stdout? EvoSuite can provide inputs to the class under test through a modified System.in, but there's no way for it to check System.out since EvoSuite is intended to generate unit tests by calling/checking the API (what you're asking is essentially system testing). If you want unit tests, I suggest you add an API that makes your class testable with assertions.