我有一个类 FTPOperation,我用它作为基类来重新组合 FTP 操作常用的方法。其中一种方法是 connect()。
public abstract class FtpOperation {
protected static final Log log = LogFactory.getLog(FtpOperation.class);
/**
* Hostname or IP address of the FTP server (e.g. localhost, 127.0.0.1).
*/
private String hostName;
private String username;
private String password;
protected FTPClient ftpClient = getFTPClient();
public void setHostName(String hostName) {
this.hostName = hostName;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
/**
* Connect to the specified FTP server.
*
* @throws Exception
*/
protected void connect() throws Exception {
int reply;
// Connect to the FTP server
ftpClient.connect(hostName);
if (!ftpClient.login(username, password))
throw new Exception("Fail to log in with the given credentials.");
log.info("Connected to " + hostName + ".");
log.info(ftpClient.getReplyString());
// Check if the connection succeeded
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
throw new Exception("Connection to FTP server failed with code "
+ reply + ".");
}
/**
* Used for mocking.
*
* @return
*/
protected FTPClient getFTPClient() {
if (this.ftpClient == null)
this.ftpClient = new FTPClient();
return ftpClient;
}
}
我想编写单元测试来测试这个方法,但我不知道如何测试它。我使用 Mockito 为 FTPClient 实例创建一个模拟对象。首先,我考虑过测试 ftpClient.connect() 调用返回某个异常的不同情况,但我认为这是错误的,因为我通过知道 connect() 方法的实现而不是通过 API 进行测试。在我所做的测试示例中:
@Test(expected = SocketException.class)
public void testConnectSocketException() throws Exception {
downloadInitialFileTasklet.setHostName("hostname");
doThrow(new SocketException()).when(mockFtpClient).connect("hostname");
downloadInitialFileTasklet.connect();
}
有人可以向我解释测试这种方法的正确方法吗?
谢谢