繁体   English   中英

如何在Java中测试IO问题?

[英]How to test IO issues in Java?

在不使用休眠的模拟流(因为它们会对中断做出反应)的情况下,如何在IO性能非常差的情况下测试应用程序代码的行为?

例如,我要测试一个ConcurrentWrapper实用程序,该实用程序具有用于文件IO的线程池。 它将每个操作都带有带有超时的invokeAll()提交给ExecutorService 我不仅要确认使用ConcurrentWrapper的调用在超时之前退出,还要确认它以某种方式使其内部ExecutorService的线程终止(以避免泄漏)。

我需要以某种方式模拟内部线程中的慢速IO,但是要以一种可以忽略中断的方式进行模拟(就像真正的IO一样)。

需要澄清的一点是 :不能接受“睡眠并吞下InterruptedException ”或“睡眠,赶上InterruptedException并返回睡眠”之类的答案。 我想测试我的代码如何处理中断,而这种检测将通过处理它们本身来达到目的。

您可以通过坚持通过中断睡眠的方式进行睡眠:

long start = System.currentTimeMillis();
long end = start + sleepTime;
for (long now = start; now < end; now = System.currentTimeMillis()) {
    try {
        Thread.sleep(end - now);
    } catch (InterruptedException ignored) {
    }
}

为了进行超时测试,您实际上可以为执行测试花费最大的时间,在JUnit中,您可以包括注释超时:

@Test(timeout=100)
public void method_withTimeout() {
       while(true);
}

对于测试方法退出的部分测试,您可以使用Future接口,该接口提供超时以获取结果。

如果我正确理解您的问题,ReentrantLock可能会有所帮助。

final ReentrantLock lock = new ReentrantLock();

Callable<Void> c = new Callable<Void>() {
  public void call() {
    lock.lock();

    try {

       if (Thread.currentThread().isInterrupted()) {
         ...
       }
    }
    finally {
      lock.unlock();
    }
  }
}

// Submit to the pool
Future<Void> future = executorService.submit(c);

// you might want to sleep a bit to give the pool a chance
// to pull off the queue.

// Issue a cancel
future.cancel();

// Now release the lock, which should let your
// callable continue onto to the interrupted check.
lock.unlock();

请注意,“ lock”方法不会引发任何InterruptedException(尽管有一个名为“ lockInterruptible”的方法),并且如果您查看该类的代码,它不会被捕获和吞咽(正如您所陈述的那样)成为你想成为的人)。

暂无
暂无

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

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