【发布时间】:2021-01-14 07:38:10
【问题描述】:
我有一个 SFTP 文件的方法。在该方法中,我有以下 sn-p 代码:-
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
JSch jsch = new JSch();
try (FileInputStream fileInputStream = new FileInputStream(new File(fileName));){
session = jsch.getSession(sftpUser, sftpHost, sftpPort);
session.setPassword(sftpPass);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
log.info("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
log.info("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(sftpWorkingFolder);
channelSftp.put(fileInputStream, new File(fileName).getName());
} catch (JSchException | SftpException | IOException e) {
log.error("Exception : ", e);
}
我正在为上述编写Junit 测试方法。如何模拟channelSftp 的实例,它只是带有类型转换的channel?
下面是一个sn-p的测试方法:
@MockBean
private JSch jSch;
@Mock
FileInputStream fileInputStream;
@MockBean
private Session session;
@MockBean
private Channel channel;
@MockBean
private ChannelSftp channelSftp;
PowerMockito.whenNew(JSch.class).withNoArguments().thenReturn(jSch);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(fileInputStream);
when(jSch.getSession("ddmin", "localhost:8080", 22)).thenReturn(session);
doNothing().when(session).connect();
when(session.openChannel("sftp")).thenReturn(channel);
doNothing().when(channel).connect();
doNothing().when(channelSftp).cd(any(String.class));
【问题讨论】:
-
你在做什么应该可以,你能分享一下你用什么运行测试吗? (@RunWith ..)
-
我有这个:@RunWith(MockitoJUnitRunner.class)
标签: java unit-testing junit mockito powermockito