How to pass command line arguments to Junit Test

1677
July 07, 2019, at 9:10 PM

I have a main class that accepts command line arguments and I am passing this parameter to another class. Now i have to test the myClass with parameters. I have JUnit to test it but I want to know how do pass this in the test

public class JsonFileTest {
    public static void main(String[] fileNames) {
        myClass class = new myClass(fileNames);
    }
}

I am a beginner in JUnit and learning it so if any guidance would be highly appreciated. I need to pass filenames to a class method.

Answer 1

It seems counter-intuitive that you want to parameterize your unit tests in this way. I would suggest that you think of a few sets of arguments and hardcode them in your unit tests. This way they are repeatable, and, hopefully, offer good coverage.

Answer 2

You don't need to pass command line parameters to your JUnit execution. Instead your test methods should build/prepare everything and call your new myClass(...) constructor with the parameters your original program would do when using command line parameters. The code might look like this:

@Test
public void checkForWhatever() {
    // prepare everything here like create a temp file
    File x = ...;
    String filename = x.getName(); // or maybe even x.getAbsolutePath();
    String[] arguments = new String[1];
    arguments[0] = filename;
    // now call your constructor
    myClass obj = new myClass(arguments);
    // do any checks here now
    Assertions.assertTrue(obj.getWhatever());
    // ...
}
Rent Charter Buses Company
READ ALSO
Java thread dump not detecting deadlock, no BLOCKED threads

Java thread dump not detecting deadlock, no BLOCKED threads

My server keeps running into a deadlock, and I'm not sure how to solve it

164
Creating a JAR from code WITHOUT a main class

Creating a JAR from code WITHOUT a main class

I am using IntelliJ and I would like to package a library I found into a jar for my projectSaid library was found online and only contains java files without a main class

156
How do I set a windows environment variable permanently? [duplicate]

How do I set a windows environment variable permanently? [duplicate]

This question already has an answer here:

157