Search code examples
javajunittestcase

JUnit test case for checking arguments


Edited I am learning how to write testcases using JUnit. Disclaimer: I haven't understood anything that I have found on the net regarding this. :) I wish to write a simple test case for this: I have a simple Java class that accepts arguments as parameters to the main function and prints it. There is no more to this code. Edit:

This is my main function: public static void main(String args[]) {

    //Expecting 3 arguments: 1. InputDirectory path, 2. OutputDirectory path, 3. Keys-comma separated

    checkArguments(args);

.....

private static void checkArguments(String[] args) {
    // TODO Auto-generated method stub
    if (args.length != 3) {
        try {
            System.out.println("Invalid input arguments");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }
}

}

This main function code works well. Now I need to write a test case such that I check how many inputs are there and accordingly print the message. So far, I have written this:

FilterProcessPDK checkArg = new FilterProcessPDK();
int testCheckArgRes = checkArg.checkArguments(); //I dont know how to pass the arguments to this function

@Test
public void testCheckArgs(){
    assertEquals("message", expected, actual);
}

For this, I will be giving the inputs- 1) Input path (C:/xyz/input) 2) Output path (C:/xyz/output) 3) A list of any number of "keys" ("A" or "A, j")


Solution

  • I've been writing tests with Junit since I first became aware of it in 1998, but I've never seen such a test.

    I don't think it's appropriate.

    I have to admit that I don't usually test main methods. It ought to be orchestrating a bunch of other stuff that I've tested well. By the time I get to the main method I've got sufficient coverage and confidence where I don't test input and output issues.

    A better solution is programming by contract: Have your main method enforce the pre-conditions for inputs that it requires. If users provide incorrect inputs, let them know.