使用@Capture Mockito 进行测试的问题
Problems testing with @Capture Mockito
我正在尝试用junit测试SftpSession.read方法,我不太确定测试这个方法的方法是什么,我使用的是@Captor,但我没有清楚地理解我可以实施这个测试吗?这是我的测试代码:
@Test
void getFileContent() throws IOException {
String directory = "testDirectory";
String fileName = "testFileName";
ByteArrayOutputStream fileByteStream = new ByteArrayOutputStream();
given(sessionFactory.getSession()).willReturn(sftpSession);
sftpServiceImpl.getFileContent(directory, fileName);
verify(sftpSession, times(1)).read(captor.capture(), eq(fileByteStream));
}
这是 getFileContent 方法:
@Override
public byte[] getFileContent(String directory, String fileName) throws IOException {
try (SftpSession session = sessionFactory.getSession()) {
ByteArrayOutputStream fileByteStream = new ByteArrayOutputStream();
session.read(directory + "/" + fileName, fileByteStream);
return fileByteStream.toByteArray();
}
}
你可以这样做:
verify(sftpSession, times(1)).read(any(String.class), any(ByteArrayOutputStream.class));
或
verify(sftpSession, times(1)).read(argThat (arg -> arg.contains(directory) && arg.contains(fileName) ), argThat (arg -> arg != null));
我正在尝试用junit测试SftpSession.read方法,我不太确定测试这个方法的方法是什么,我使用的是@Captor,但我没有清楚地理解我可以实施这个测试吗?这是我的测试代码:
@Test
void getFileContent() throws IOException {
String directory = "testDirectory";
String fileName = "testFileName";
ByteArrayOutputStream fileByteStream = new ByteArrayOutputStream();
given(sessionFactory.getSession()).willReturn(sftpSession);
sftpServiceImpl.getFileContent(directory, fileName);
verify(sftpSession, times(1)).read(captor.capture(), eq(fileByteStream));
}
这是 getFileContent 方法:
@Override
public byte[] getFileContent(String directory, String fileName) throws IOException {
try (SftpSession session = sessionFactory.getSession()) {
ByteArrayOutputStream fileByteStream = new ByteArrayOutputStream();
session.read(directory + "/" + fileName, fileByteStream);
return fileByteStream.toByteArray();
}
}
你可以这样做:
verify(sftpSession, times(1)).read(any(String.class), any(ByteArrayOutputStream.class));
或
verify(sftpSession, times(1)).read(argThat (arg -> arg.contains(directory) && arg.contains(fileName) ), argThat (arg -> arg != null));