如何使用try-with-resources测试方法

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


由于它在try子句中使用new运算符,因此无法对其进行模拟。我不想使用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

    }

}


芜湖不芜
浏览 178回答 1
1回答

开心每一天1111

您可以将依赖项实例化移动到工厂类中,并将其作为构造函数参数传递给要测试的代码。工厂类本身太简单而不会失败,因此不需要进行测试。您是否打算做类似的事情:try (FileInputStream fis = getCreatedFromFactory(file)) ??– JavaIntern几乎...@Singletonpublic 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();    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java