Reputation: 35
I wrote a Java class in which one try to access to a FTP.
I work on Eclipse and I want to make a Junit test on that. I know how to test public classes but I'm stuck at testing a static void main method.
Here is my ftp.java class :
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 :
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 !
Upvotes: 1
Views: 10350
Reputation: 109547
@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.
Upvotes: 1
Reputation: 880
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.
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.
Upvotes: 2