在我的配置中
@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;
}在我的代码中,我将其命名为:List<SftpFileInfo> remoteFiles = sftpGateway.readListOfFiles("payload"),并使用SftpFileInfo中的文件名执行一些操作。在我的测试中,我想模拟网关并返回特定的文件名;我的测试中有这样的内容:
ChannelSftp.LsEntry lsEntry = new ChannelSftp().new LsEntry("filename", "filename", null);
Mockito.when(sftpMessagingGateway.readListOfFiles(Mockito.anyString())).thenReturn(List.of(new SftpFileInfo(lsEntry)));我需要使模拟返回一个带有文件名的SftpFileInfo,以便能够正确地运行我的代码,我查看了这个类并看到:
LsEntry(String filename, String longname, SftpATTRS attrs){
setFilename(filename);
setLongname(longname);
setAttrs(attrs);
}我有办法在我的测试中做到这一点吗?目前,我无法设置LsEntry,因为它不能在包之外被访问。
回答后:
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);发布于 2021-02-02 22:08:31
在Spring集成测试中,我们确实这样做了:
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);我认为类似的东西也适用于你的模仿者。
另一种方法是直接模仿它:
LsEntry lsEntry = mock(LsEntry.class);
SftpATTRS attributes = mock(SftpATTRS.class);
when(lsEntry.getAttrs()).thenReturn(attributes);
when(lsEntry.getFilename()).thenReturn(fileName);https://stackoverflow.com/questions/66018053
复制相似问题