繁体   English   中英

如何编写单元测试来验证我的缓冲区(资源)是否正确释放

[英]How to write a unit test to verify my buffers(resources) are properly released

我想知道如何编写一个好的单元测试来验证我在方法中分配的缓冲区在所有情况下都正确释放。 一般来说,这就是我想要实现的目标。

// Some pseudo code I imagine
public void performSomeIO() {
  // A better way may be to use try-with-resource but not everything is Closeable
  // Maybe you will say "Wrap it with a Closeable if it is not"?
  Buffer bytebuf = SomeUtility.allocateBuffer(...);
  try {
    // do some IO
    read(byteBuf);
  } catch (SomeException e) {
    // Some handling
  } finally {
    // I guess the rule of thumb is the buffer should be properly closed in the
    // finally section, but you cannot expect everyone to follow this pattern.
    // For example I find memory leak in an old program and I'd like to detect
    // that and add a guard on the scenario so that does not happen anymore.
    // Imagine this finally section does not exist, what kind of unit test do I add
    // to ensure the buffer is released? In other words, if someone removes the
    // finally section, the test will start alerting.
    bytebuf.release();
  }
}

我发现跟踪仅在方法内部的资源并不容易。 是否有任何经验法则,无论是关于如何验证内部资源(如缓冲区或更一般的任何东西)的生命周期,还是关于如何在单元测试级别避免缓冲区泄漏?

谢谢!

首先使SomeUtility成为一个接口,并在该接口上allocateBuffer一个方法,以获得更好的可测试性。 您需要将SomeUtility实例注入每个分配缓冲区的组件中。

然后你可以像这样测试每个方法(这个测试是为 JUnit 4 编写的):

class TestIoPerformer {
    @Rule
    public MockitoRule rule = MockitoJUnit.rule();

    @Mock
    private SomeUtility someUtility;

    @Mock
    Buffer buffer;

    @InjectMocks
    private IoPerformer ioPerformer;

    @Test
    public void testBufferReleased() {
      when(someUtility.allocateBuffer(...)).thenReturn(buffer);
      // mock Buffer behaviour if necessary
      ioPerformer.performSomeIO();
      verify(buffer).release();
    }
}

这只是测试通过您的代码的一条路径。 您将需要对其他路径进行单独测试,例如read()抛出异常。

为了让人们更容易做正确的事情,你可以让你的Buffer实现Closeable并鼓励客户使用 try-with-resources 模式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM