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

时间:2018-07-09 08:41:56

标签: java unit-testing junit mocking mockito

如何对使用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
    }
}

1 个答案:

答案 0 :(得分:1)

您可以将依赖实例化移动到 factory 类中,并将其作为 constructor参数传递给被测代码。工厂类本身很容易失败,因此不需要进行测试。

  

您是否打算做类似的事情:

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