简体   繁体   English

Java-使用JUnit测试公共静态void主方法

[英]Java - test a public static void main method with JUnit

I wrote a Java class in which one try to access to a FTP. 我写了一个Java类,其中一个尝试访问FTP。
I work on Eclipse and I want to make a Junit test on that. 我在Eclipse上工作,我想对此进行Junit测试。 I know how to test public classes but I'm stuck at testing a static void main method. 我知道如何测试公共类,但是我只能测试静态的void main方法。

Here is my ftp.java class : 这是我的ftp.java类:

public class ftp {

    public static void main(String[] args) {
        FTPClient client = new FTPClient();

        try {
            client.connect("host");

            // Try to login and return the respective boolean value
            boolean login = client.login("login", "pass");

            // If login is true notify user
            if (login) {
                System.out.println("Connection established...");

                // Try to logout and return the respective boolean value
                boolean logout = client.logout();

                // If logout is true notify user
                if (logout) {
                    System.out.println("Connection close...");
                }
                //  Notify user for failure
            } else {
                System.out.println("Connection fail...");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // close connection
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

I began to create the ftpTest.java like that : 我开始像这样创建ftpTest.java:

public class ftpTest {

    ftp testaccess = new ftp();
    FTPClient testclient = ftp.client;


    @Test
    public void testftp() {
        fail("Not yet implemented");
    }

}

Any help would be very appreciated. 任何帮助将不胜感激。
Thanks ! 谢谢 !

Since you are not using the command-line arguments, and nor I see any env explicit properties, you refactor the code and move everything to a separate method(s) and test it there. 由于您没有使用命令行参数,也没有看到任何env显式属性,因此您可以重构代码并将所有内容移至单独的方法并在此处进行测试。

If you want to do an integration test you might have to spin a full-blown ftp server but that's a bit out of scope for unit tests. 如果要进行集成测试,则可能必须旋转功能全面的ftp服务器,但这在单元测试的范围之外。

@Test
public void testftp() {
    FtpClient.main(new String[0]);
}

That of course is a bit disappointing. 当然,这有点令人失望。

@Test
public void testftp() {
    PrintStream old = System.out;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(baos);
    System.setOut(out);
    FtpClient.main(new String[0]);
    System.out.flush();
    System.setOut(old);
    String s = new String(baos.toByteArray(), Charset.defaultCharset());
    ... check s
}

Capturing the output can give more insight. 捕获输出可以提供更多的见解。

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

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