如何用资源测试方法



如何对使用try with resources的方法进行单元测试?

由于它在try子句中使用了新的运算符,所以我不能嘲笑它。我不想使用PowerMock。似乎唯一的方法就是创建集成测试?

public void methodToBeTested(File file) {
try (FileInputStream fis = new FileInputStream(file)) {
//some logic I want to test which uses fis object
} catch (Exception e) {
//print stacktrace
}
}

您可以将依赖项实例化移动到工厂类中,并将其作为构造函数参数传递给测试中的代码。工厂类本身将是太简单而不能失败,因此不需要进行测试。

你打算做一些类似的事情吗:

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(); 
}
}

最新更新