Jordendarc
Jordendarc

Reputation: 37

How to return SftpFileInfo from a mock? Junit5 Java11 spring-integration

in my config

    @MessagingGateway
    public interface SftpMessagingGateway {
        @Gateway(requestChannel = "listFiles")
        List<SftpFileInfo> readListOfFiles(String payload);
    }
    @Bean
    @ServiceActivator(inputChannel = "listFiles")
    public MessageHandler sftpReadHandler(){
        SftpOutboundGateway sftpOutboundGateway = new SftpOutboundGateway(sftpSessionFactory(), "ls", remoteDirectory);
        return sftpOutboundGateway;
    }

in my code I call this : List<SftpFileInfo> remoteFiles = sftpGateway.readListOfFiles("payload") and use the filename in SftpFileInfo to perform some actions. In my test, I want to mock the gateway and return specific filenames; I have this in my test:

        ChannelSftp.LsEntry lsEntry = new ChannelSftp().new LsEntry("filename", "filename", null);
        Mockito.when(sftpMessagingGateway.readListOfFiles(Mockito.anyString())).thenReturn(List.of(new SftpFileInfo(lsEntry)));

I would need to make the mock return a SftpFileInfo with an LsEntry with a filename to be able to run through my code properly and I looked into the class and see:

    LsEntry(String filename, String longname, SftpATTRS attrs){
      setFilename(filename);
      setLongname(longname);
      setAttrs(attrs);
    }

is there a way for me to do this within my test? Currently, I cannot set up a LsEntry because it cannot be accessed outside of the package

after answer:

ChannelSftp.LsEntry lsEntry = mock(ChannelSftp.LsEntry.class);
SftpATTRS attributes = mock(SftpATTRS.class);
when(lsEntry.getAttrs()).thenReturn(attributes);
when(lsEntry.getFilename()).thenReturn("file");
SftpFileInfo fileInfo = new SftpFileInfo(lsEntry);
List<SftpFileInfo> sftpFileInfoList = List.of(fileInfo);
Mockito.when(sftpMessagingGateway.readListOfFiles(Mockito.anyString())).thenReturn(sftpFileInfoList);

Upvotes: 1

Views: 964

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121542

We do like this in Spring Integration tests:

SftpATTRS attrs = mock(SftpATTRS.class);
Constructor<LsEntry> ctor = (Constructor<LsEntry>) LsEntry.class.getDeclaredConstructors()[0];
ctor.setAccessible(true);
LsEntry sftpFile1 = ctor.newInstance(channel, "foo", "foo", attrs);

I think something similar should work for your mocks, too.

Another way is just to mock it directly:

LsEntry lsEntry = mock(LsEntry.class);
SftpATTRS attributes = mock(SftpATTRS.class);
when(lsEntry.getAttrs()).thenReturn(attributes);
when(lsEntry.getFilename()).thenReturn(fileName);

Upvotes: 1

Related Questions