简体   繁体   English

通过此JUnit测试

[英]Making this JUnit Test pass

Here is the test: 这是测试:

@Test
public void invalidPort() {
    try {
        SS.main(SS_ARGS);
        assertTrue(false);
    } catch (Exception e) {
        assertTrue(true);
    }
}

Here is the relevant code in SS: 这是SS中的相关代码:

public static void main(String[] args) {
    try {

        if (obj.start() == 0) {
            ...stuff
        }
    } catch (BindException e) {
        System.out.println("Address already in use.");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

This is what obj.start() does: 这是obj.start()的作用:

public int start() {
    try {
        HttpServer server = HttpServerFactory.create(serverURI);
        this.server = server;
        server.start();
        return 0;
    } catch (NullPointerException e) {
        System.out.println("Error: Please specify the server URI");
        return 1;
    } catch (Exception e) {
        System.out.println("Error: Invalid port!");
        return 1;
    }


}

In this test I am making sure that the port is invalid. 在此测试中,我确保端口无效。 When run, the program prints out "Error: Invalid port!" 运行时,程序将打印出“错误:端口无效!”。 which is good, but the test doesn't pass. 很好,但是测试没有通过。 It fails because it reaches the assertTrue(false) line. 它失败,因为它到达了assertTrue(false)行。 How can I make this test pass? 我如何才能通过此考试?

If you catch all the relevant exceptions in your main method, the main method will not throw an exception and so your test always fails (because it expects an exception to be thrown). 如果您在main方法中捕获了所有相关的异常,则main方法将不会引发异常,因此您的测试始终会失败(因为它期望引发异常)。

The console output that you mention comes from the catch block of the exception. 您提到的控制台输出来自异常的catch块。 If you catch the exception, it is gone and will not be passed to the test. 如果您捕获到异常,则该异常将消失并且不会传递给测试。

Generally, it is advisable to construct small, testable methods with input and output values. 通常,建议使用输入和输出值构造小的可测试方法。 Testing output for the user (like console output) should usually be avoided. 通常应避免为用户测试输出(如控制台输出)。 By separating the logic as much as possible from the output, one can test thoroughly without having the problems mentioned above. 通过将逻辑与输出尽可能地分离,可以彻底测试而不会出现上述问题。

@Test(expected=IllegalStateException.class)
public void invalidPort() {
        SS.main(SS_ARGS);
}

Replace IllegalStateException with the actual exception implementation that you're expecting. 将IllegalStateException替换为所需的实际异常实现。 (Perhaps you should be throwing an exception from your main method, rather than just logging it to stderr?) (也许您应该从主方法中抛出异常,而不是仅将其记录到stderr?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM