Passing command line arguments to JUnit in Eclipse

拜拜、爱过 提交于 2020-01-07 02:04:10

问题


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


回答1:


To test your class main method simply write something like:

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



回答2:


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();
}



回答3:


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



来源:https://stackoverflow.com/questions/4208415/passing-command-line-arguments-to-junit-in-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!