我试图模拟一个byte,但是在这个方法中,这个值是null。我使用eq()方法发送测试此方法所需的byte[]。
这是我的方法的签名:
@Override
public void addFile(String directory, String fileName, byte[] content) throws IOException {
try (SftpSession session = sessionFactory.getSession()) {
makeSureDirectoryIsAvailable(session, directory);
InputStream fileByteStream = new ByteArrayInputStream(content);
session.write(fileByteStream, directory + "/" + fileName);
}
}当我查看content变量时,它是null,字符串是空的,我不太确定如何模拟这个值,接下来是我的测试代码,我使用的是JUnit 5。
package service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.integration.sftp.session.DefaultSftpSessionFactory;
import org.springframework.integration.sftp.session.SftpSession;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.given;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class SFTPServiceImplTest {
@Mock
SftpSession sftpSession;
@Mock
DefaultSftpSessionFactory sessionFactory;
private SFTPServiceImpl sftpServiceImpl;
@BeforeEach
public void init() {
MockitoAnnotations.initMocks(this);
sftpServiceImpl = new SFTPServiceImpl(sessionFactory);
}
@Test
void addFile() throws Exception {
byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};
given(sessionFactory.getSession()).willReturn(sftpSession);
given(sftpSession.exists(anyString())).willReturn(false);
sftpServiceImpl.addFile(anyString(), anyString(),eq(bytes));
}
@Test
void getFileContent() {
}
@Test
void deleteFile() {
}
@Test
void moveFile() {
}
@Test
void listFiles() {
}
}发布于 2020-01-16 05:05:57
如果您正在尝试测试sftpServiceImpl.addFile(),那么您就做错了。您不应该将anyString()和eq(bytes)传递给您正在测试的方法。
相反,我将建议使用ArgumentCaptor,并查看是否使用正确的参数调用了session.write() (实际上是传递给了sftpServiceImpl.addFile())
代码将如下所示-
@Mock
SftpSession sftpSession;
@Mock
DefaultSftpSessionFactory sessionFactory;
@Captor
ArgumentCaptor<InputStream> captor;
private SFTPServiceImpl sftpServiceImpl;
@BeforeEach
public void init() {
MockitoAnnotations.initMocks(this);
sftpServiceImpl = new SFTPServiceImpl(sessionFactory);
}
@Test
void addFile() throws Exception {
byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};
given(sessionFactory.getSession()).willReturn(sftpSession);
given(sftpSession.exists(anyString())).willReturn(false);
String directory = "testDirectory";
String fileName = "testFileName";
sftpServiceImpl.addFile(directory, fileName, bytes);
verify(sftpSession, times(1)).write(captor.capture(), eq(directory + "/" + fileName));
// you need to compare the byte arrays here
assertArrayEquals(bytes, captor.getValue());
}希望这是有意义的。
https://stackoverflow.com/questions/59759333
复制相似问题