1 回答
TA贡献1836条经验 获得超13个赞
您可以将依赖项实例化移动到工厂类中,并将其作为构造函数参数传递给要测试的代码。工厂类本身太简单而不会失败,因此不需要进行测试。
您是否打算做类似的事情:
try (FileInputStream fis = getCreatedFromFactory(file)) ??
– JavaIntern
几乎...
@Singleton
public class InputStreamFactory { // too simple to fail -> no UnitTests
public InputStream createFor(File file) throws IOException, FileNotFoundException {
retrun new FileInputStream(file);
}
}
class UnitUnderTest {
private final InputStreamFactory inputStreamFactory;
UnitUnderTest(@Inject InputStreamFactory inputStreamFactory){
this.inputStreamFactory=inputStreamFactory;
}
public void methodToBeTested(File file) {
try (FileInputStream fis = inputStreamFactory.createFor(file)) {
//some logic I want to test which uses fis object
} catch (Exception e) {
//print stacktrace
}
}
}
class UnitUnderTestTest{
@Rule
public MockitoRule rule = MockitoJUnit.rule();
@Mock
private InputStreamFactory inputStreamFactory;
@Mock
private InputStream inputStream;
private final File inputFile = new File("whatever");
// no init here, mock for inputStream not yet created
private UnitUnderTest unitUnderTest;
/* I don't use @InjectMocks
since it does not cause compile error
if constructor misses parameter */
@Before
public void setup() {
unitUnderTest = new UnitUnderTest(inputStreamFactory);
doReturn(inputStream).when(inputStreamFactory).createFor(any(File.class);
}
@Test
public void createsInputStreamFromFilePassed() {
// arrange
/* nothing to do */
// act
new UnitUnderTest(inputStreamFactory).methodToBeTested(inputFile);
// assert
verify(inputStreamFactory).createFor(inputFile);
verify(inputStream).close();
}
}
添加回答
举报