【问题标题】:how to test method with try-with-resources如何使用 try-with-resources 测试方法
【发布时间】:2018-07-09 08:41:55
【问题描述】:

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

【问题讨论】:

  • 请用具体代码说明您的问题。
  • 您可以将依赖项实例化移动到 工厂类 并将其作为 构造函数参数 传递给您的测试代码。工厂类本身会太简单而无法失败,因此不需要进行测试。
  • @davidxxx 示例代码插入
  • @TimothyTruckle 你是否建议这样做:try (FileInputStream fis = getCreatedFromFactory(file)) ??

标签: java unit-testing junit mocking mockito


【解决方案1】:

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

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

try (FileInputStream fis = getCreatedFromFactory(file)) ??

–Java实习生

几乎……

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多