name_masked
name_masked

Reputation: 9803

Passing command line arguments to JUnit in Eclipse

All,

I am currently using JUnit 4 for writing test cases. I am fairly new to JUnit and finding it difficult to test my main class which takes arguments. I have specified the arguments to my JUnit test class by:

1 > Right click JUnit test class
2 > Goto Run As -> Run Configurations
3 > Select the Arguments tab and specify a value (I have entered an invalid argument i.e. the main class expects the command line argument to be converted to an int and I am passing a String value that cannot be converted to int)

However, the main class that I am testing, if the command line argument cannot be converted to a int, than I throw IllegalArgumentException. However, the JUnit does not show the testMain() method as Error or Failure. I don't think my setup is right for the JUnit class. Can anyone please guide me where I am going wrong

Upvotes: 0

Views: 6234

Answers (3)

Laksitha Ranasingha
Laksitha Ranasingha

Reputation: 4507

Firstly the arguments should be in the program arguments section. Normally the launching point of the application that's the main method doesn't need to be tested if you design the app to be testable.

  1. Refactor the class

    
    public static class ArgumentValidator
        {
            public static boolean nullOrEmpty(String [] args)
            {
                 if(args == null || args.length == 0)
                 {
                     throw new IllegalArgumentException(msg);
                 }
                 //other methods like numeric validations
            }
         }
    
  2. You can now easily test the nullOrEmpty method using junit like


@Test(expected = IllegalArgumentException.class)

    public void testBadArgs()
    {
         ArgumentValidator.nullOrEmpty(null);
    }

I think this is a better approach

Upvotes: 0

Osvaldo
Osvaldo

Reputation: 96

To test your class main method simply write something like:

@Test(expected = IllegalArgumentException.class)
public void testMainWithBadCommandLine()
{
     YourClass.main(new String[] { "NaN" });
}

Upvotes: 2

Kelly S. French
Kelly S. French

Reputation: 12354

Change the main() method to something like this:

public static void main(String[] args)
{
  MyClass myclass = new MyClass(args);
  myclass.go();
}

Move the code that was in main() to the new method go(). Now, your test method can do this:

public void myClassTest()
{
  String[] args = new String[]{"one", "two"}; //for example
  MyClass classUnderTest = new MyClass(testArgs);
  classUnderTest.go();
}

Upvotes: 1

Related Questions