简体   繁体   English

Mockito和FTPClient JUnit模拟测试

[英]Mockito and FTPClient JUnit mocked test

I am working on a personal project to create an FTP client using Java and JavaScript. 我正在一个个人项目中,使用Java和JavaScript创建FTP客户端。

I started by creating the FTPController class which uses commons-net/FTPClient. 我首先创建使用commons-net / FTPClient的FTPController类。

Here's an exemple of my code: 这是我的代码的一个示例:

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
}

The FtpController does its work correctly in a Junit class using a local FTP server but when the server goes down the tests fail. FtpController使用本地FTP服务器在Junit类中可以正常工作,但是当服务器关闭时,测试将失败。

I used Mockito to do my test but it always shows Connection timeout . 我使用Mockito进行测试,但始终显示Connection timeout

My class test follows this: 我的课堂测试是这样的:

...
@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);
}

Okay, so first thing is you're testing FTPController, not FTPClient. 好的,所以第一件事是您正在测试FTPController,而不是FTPClient。

  • Remove annotations from FTPController and FTPClient in your test class 在测试类中从FTPController和FTPClient删除注释
  • Annotate FtpController with @InjectMocks 用@InjectMocks注释FtpController
  • Annotate FTPClient with @Mock Now you would have stubbed out FtpClient and mockito will set the private member of FTPClient member of FTPController to the mock. 用@Mock注释FTPClient现在,您可以将FtpClient删除,并且嘲讽会将FTPController的FTPClient成员的私有成员设置为模拟对象。

If I am correct in my assumption that FtpController and will return true if ftpClient.storeFile returns true then your test should work without a server. 如果我对FtpController的假设是正确的,并且如果ftpClient.storeFile返回true,则返回true,那么您的测试应该在没有服务器的情况下进行。

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

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