Passing command line arguments to JUnit in Eclipse

2019-09-14 22:22发布

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

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-09-14 22:45

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

查看更多
等我变得足够好
3楼-- · 2019-09-14 22:59

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();
}
查看更多
你好瞎i
4楼-- · 2019-09-14 23:02

To test your class main method simply write something like:

@Test(expected = IllegalArgumentException.class)
public void testMainWithBadCommandLine()
{
     YourClass.main(new String[] { "NaN" });
}
查看更多
登录 后发表回答