我有
@Component
public class CodesConverterService {
private final FileInputStreamFactory fileInputStreamFactory;
public CodesConverterService(FileInputStreamFactory fileInputStreamFactory, YamlFactory yamlFactory) {
this.fileInputStreamFactory = fileInputStreamFactory;
}
@EventListener(ApplicationReadyEvent.class)
public void loadMappingsFromSource() {
try {
FileInputStream f = fileInputStreamFactory.getStream("mappingFile");
} catch (Exception e) {
throw new CodesConverterException("Can`t load mappings from source");
}
}
我的文件输入流工厂:
@Component
public class FileInputStreamFactory {
public FileInputStream getStream(final String file) throws FileNotFoundException {
return new FileInputStream(file);
}
}
我的测试
@RunWith(SpringRunner.class)
public class CodesConverterServiceTest {
@InjectMocks
private CodesConverterService codesConverterService;
@Mock
private FileInputStreamFactory fileInputStreamFactory;
@Mock
private FileInputStream fileInputStream;
@Test
public void whenLoadMappingsFromSource_GoodPath() throws FileNotFoundException {
when(fileInputStreamFactory.getStream("mappingFile")).thenReturn(fileInputStream);
this.codesConverterService.loadMappingsFromSource();
}
为什么我的 f 总是 null?我尝试过很多变化。但它始终为空。我为 FileInputStream 创建了工厂,因为我不想在测试中使用 PowerMock 来模拟新 FileInputStream 的创建。
最佳答案
我在下面的示例中重现了您的测试,这对我有用。
(使用 JUnit 4
和 Mockito
3.0.0
和 2.28.2
进行验证)
我唯一改变的是Runner
,但根据您的评论,您已经这样做了。
我删除了示例中的注释,因为当使用 MockitoJUnitRunner
执行测试时它们应该是不相关的,并更改了 loadMappingsFromSource
的返回类型以轻松添加该 Assert.assertNotNull
。
我还用 RuntimeException
替换了 CodesConverterException
。
这些更改都不会影响测试本身。
即使只有带有参数的构造函数,FileInputStream
的 mock
也已正确创建。
@RunWith(MockitoJUnitRunner.class)
public class CodesConverterServiceTest {
class YamlFactory {
}
class FileInputStreamFactory {
public FileInputStream getStream(final String file) throws FileNotFoundException {
return new FileInputStream(file);
}
}
static class CodesConverterService {
private final FileInputStreamFactory fileInputStreamFactory;
public CodesConverterService(FileInputStreamFactory fileInputStreamFactory, YamlFactory yamlFactory) {
this.fileInputStreamFactory = fileInputStreamFactory;
}
public FileInputStream loadMappingsFromSource() {
try {
return fileInputStreamFactory.getStream("mappingFile");
} catch (Exception e) {
throw new RuntimeException("Can`t load mappings from source");
}
}
}
@InjectMocks
private CodesConverterService codesConverterService;
@Mock
private FileInputStreamFactory fileInputStreamFactory;
@Mock
private FileInputStream fileInputStream;
@Test
public void whenLoadMappingsFromSource_GoodPath() throws FileNotFoundException {
Mockito.when(fileInputStreamFactory.getStream("mappingFile")).thenReturn(fileInputStream);
Assert.assertNotNull(codesConverterService.loadMappingsFromSource());
}
}
关于java - 无法模拟 FileInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430893/