我有一个包含私有 ExecutorService 实例的类。在类中,我有一个方法运行提交方法并捕获 RejectedExecutionException。但是,我在模拟 ExecutorService 实例以引发异常以便我可以完成测试覆盖率时遇到了麻烦。我正在使用 JMockit 1.45。
我已经浏览过 JMockit 教程和其他网站;无论我使用@Mocked、@Capturing,还是创建一个新的假类,它似乎都不起作用。
// Implemented Class:
public class TaskRegister {
private ExecutorService executor;
public TaskRegister() {
this.executor = Executors.newFixedThreadPool(5);
}
public void executeTask(Runnable task) {
try {
this.executor.submit(task);
} catch (RejectedExecutionException e) {
System.out.println(e.getMessage);
}
}
}
// Unit Test Class:
public class TestTaskRegister {
@Tested
private TaskRegister tested;
private static int counter;
@Test // this works
public void runNormalTask() throws InterruptedException {
counter = 0;
Runnable mockTask = new Runnable() {
counter++;
}
tested.executeTask(mockTask);
Thread.sleep(100); // Allow executor to finish other thread.
assertEquals(1, counter);
}
@Test // this doesn't work, will have missing invocation error.
public void throwsError (@Capturing ExecutorService executor) throws InterruptedException {
counter = 0;
// somehow the tested class still runs the actual executor
// and not the mocked one.
new Expectations() {{
executor.submit((Runnable) any);
result = new RejectedExecutionException();
}};
Runnable mockTask = new Runnable() {
// some task
}
tested.executeTask(mockTask);
Thread.sleep(100);
assertEquals(0, counter);
}
}
我希望 @Capturing 拦截真正的执行程序实现并在调用 executor.submit 时抛出异常,但它没有这样做。
万千封印
慕娘9325324
相关分类