在Eclipse中将命令行参数传递给JUnit
全部, 我目前正在使用JUnit4编写测试用例。我对JUnit相当陌生,发现很难测试我的主类,它接受参数。我已通过以下方式指定JUnit测试类的参数: 1>右键单击JUnit测试类在Eclipse中将命令行参数传递给JUnit,junit,command-line-arguments,Junit,Command Line Arguments,全部, 我目前正在使用JUnit4编写测试用例。我对JUnit相当陌生,发现很难测试我的主类,它接受参数。我已通过以下方式指定JUnit测试类的参数: 1>右键单击JUnit测试类 2>转到运行方式->运行配置 3>选择Arguments选项卡并指定一个值(我输入了一个无效的参数,即主类希望命令行参数转换为int,而我传递的字符串值无法转换为int) 但是,如果命令行参数无法转换为int,我正在测试的main类就会抛出IllegalArgumentException。但是,JUnit不会将tes
2>转到运行方式->运行配置
3>选择Arguments选项卡并指定一个值(我输入了一个无效的参数,即主类希望命令行参数转换为
int
,而我传递的字符串值无法转换为int
)
但是,如果命令行参数无法转换为int
,我正在测试的main
类就会抛出IllegalArgumentException
。但是,JUnit不会将testMain()方法显示为错误
或失败
。我认为我的设置不适合JUnit类。有人能告诉我哪里出了问题吗将main()方法更改为以下内容:
public static void main(String[] args)
{
MyClass myclass = new MyClass(args);
myclass.go();
}
将main()中的代码移动到新方法go()。现在,您的测试方法可以做到这一点:
public void myClassTest()
{
String[] args = new String[]{"one", "two"}; //for example
MyClass classUnderTest = new MyClass(testArgs);
classUnderTest.go();
}
将main()方法更改为类似以下内容:
public static void main(String[] args)
{
MyClass myclass = new MyClass(args);
myclass.go();
}
将main()中的代码移动到新方法go()。现在,您的测试方法可以做到这一点:
public void myClassTest()
{
String[] args = new String[]{"one", "two"}; //for example
MyClass classUnderTest = new MyClass(testArgs);
classUnderTest.go();
}
要测试类main方法,只需编写如下内容:
@Test(expected = IllegalArgumentException.class)
public void testMainWithBadCommandLine()
{
YourClass.main(new String[] { "NaN" });
}
要测试类main方法,只需编写如下内容:
@Test(expected = IllegalArgumentException.class)
public void testMainWithBadCommandLine()
{
YourClass.main(new String[] { "NaN" });
}
首先,参数应该在程序参数部分。通常,如果您将应用程序设计为可测试的,则作为主要方法的应用程序的启动点不需要进行测试
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
}
}
我认为这是一种更好的方法首先,参数应该在程序参数部分。通常,如果您将应用程序设计为可测试的,则作为主要方法的应用程序的启动点不需要进行测试
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
}
}