簡體   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