How to mock a sftp session

I am updating a few tests. The Before gets the sftp session. For this, the username and password have been hardcoded in the properties file. Due to security reasons, the password cannot be checked in and has to be blanked out. However the unit test fails at

private DefaultSftpSessionFactory sftpClientFactory;
private  SftpSession sftpSession;

 public void setup() {
    sftpSession = sftpClientFactory.getSession();

This step fails with “either a password or private key is required”.I would like to get a mock session, so that I dont have to provide a password.


Regarding the unanswered/able question What’s the best mock framework for Java?, a Mockito approach would be:

  1. Get the needed libraries into your (test) class path. (

  2. Mock the SftpSession. (Via annotation private @Mock SftpSession sftpSession; …plus the according initialization/enablement, or (manually) via sftpSession = Mockito.mock(SftpSession.class);)

    a. See, whether the SessionFactory is needed (for test) at all, if so also mock.

  3. Mock/verify/reset any interactions (within your tests) with the mocked objects. (Like Mockito.when(,y,z)).then... or Mockito.verify(sftpSession, Mockito.times(n)).foo(x,y,z);)

Further reading:

Leave a Reply

Your email address will not be published. Required fields are marked *