繁体   English   中英

Mockito和FTPClient JUnit模拟测试

[英]Mockito and FTPClient JUnit mocked test

我正在一个个人项目中,使用Java和JavaScript创建FTP客户端。

我首先创建使用commons-net / FTPClient的FTPController类。

这是我的代码的一个示例:

public class FtpController {
 private FTPClient ftpClient;
 public boolean connect() { ... //do the connection }
 public boolean disconnect() { ... }
 public boolean store(String localNameAndPath, String remotePath, String newFilename) { ... // it call ftpClient.storeFile(...)}
 ... // other methods
}

FtpController使用本地FTP服务器在Junit类中可以正常工作,但是当服务器关闭时,测试将失败。

我使用Mockito进行测试,但始终显示Connection timeout

我的课堂测试是这样的:

...
@Mock
FtpController ftpController;
@InjectMocks
FTPClient ftpClient;

@BeforeEach
void setUp() {
    initMocks(this);
}

@Test
void store() throws Exception {
    String remotePath = "a1/";
    String remoteFilename = "xyz.jpg";
    String localPathOfFile = "src/test/resources/f.jpg";
    boolean expected = true;
    when(ftpClient.storeFile(localPathOfFile, remotePath + remoteFilename)).theReturn(true);
    boolean result = ftpController.store(localPathOfFile, remotePath, remoteFilename);
    assertEquals(expected, result);
}

好的,所以第一件事是您正在测试FTPController,而不是FTPClient。

  • 在测试类中从FTPController和FTPClient删除注释
  • 用@InjectMocks注释FtpController
  • 用@Mock注释FTPClient现在,您可以将FtpClient删除,并且嘲讽会将FTPController的FTPClient成员的私有成员设置为模拟对象。

如果我对FtpController的假设是正确的,并且如果ftpClient.storeFile返回true,则返回true,那么您的测试应该在没有服务器的情况下进行。

暂无
暂无

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

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