简体   繁体   中英

Mockito and FTPClient JUnit mocked test

I am working on a personal project to create an FTP client using Java and JavaScript.

I started by creating the FTPController class which uses commons-net/FTPClient.

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.

I used Mockito to do my test but it always shows 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.

  • Remove annotations from FTPController and FTPClient in your test class
  • Annotate FtpController with @InjectMocks
  • 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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