如何对java main方法进行单元测试?

dev*_*ose 5 java junit4

我有一个类,我必须通过它的 main 方法传递 2 个参数,如果传递的参数少于 2 个,它会显示一条系统错误消息。我在这里为主方法编写了一个单元测试,当我运行测试时,它停止在“运行”(显示既不通过也不失败)。请建议。

示例.java

public class Example 
{
    private static String str1   = null;
    private static String str2   = null;

    public static void main(String[] args)
    {
        if( args.length != 2 )
        {
            call();
        }

        Example ex = new Example(args[0], args[1]);
        ex.getData();
    }

    public Example(String str1, String str2)
    {
        Example.str1 = str1;
        Example.str2 = str2;
    }

    public void getData(){
        System.out.println("Name is: "+str1);
        System.out.println("City is: "+str2);
    }

    private static void call()
    {
        System.err.println("Usage: String1 String2");
        System.err.println("Where: ");
        System.err.println("       String1 - Name");
        System.err.println("       String1 - City");
        System.exit(1);
    }   
}
Run Code Online (Sandbox Code Playgroud)

示例测试.java

public class ExampleTest {
    @Test
    public void testPassingWrongNumberOfInputs() {
        StringBuffer sb = new StringBuffer();
        sb.append("Usage: String1 String2")
        .append("Where: ")
        .append("       String1 - Name")
        .append("       String1 - City");

        String expectedErrorMessage = sb.toString();

        ByteArrayOutputStream outContent = new ByteArrayOutputStream();
        System.setErr(new PrintStream(outContent));
        String[] args = {"one"};
        Example.main(args);

        assertEquals(expectedErrorMessage, outContent.toString());
    }
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*oke 0

删除 System.exit(1) 调用,您不需要它。无论如何,您的应用程序都会在 main() 完成后退出,而无需进行不必要的调用来显式终止 VM。此调用很可能会导致您的 JUnit 在到达 assertEquals 语句之前停止执行,因为您刚刚告诉 VM 退出。