我有以下的方法,它运行良好。 我正在尝试测试抛出InterruptedException的情况。这是我目前的测试方式,如果我只运行这个单独的测试就会起作用。 但是,如果我要运行测试类中剩余的5个测试,则有些测试开始失败。 当我单独运行它们时,所有测试都通过,因此很明显我的测试中的线程中断影响了其他测试。 如何编写测试,使其不影响其他测试?
@Component
class A{
@Autowired
private Helper helper;
private static ExecutorService executor = Executors.newFixedThreadPool(10);
// static variable in class
private final Future<String> number = executor.submit(() -> helper.method());
//method to be tested
public String getNumber() {
try {
return this.number.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CustomException1();
} catch (ExecutionException e) {
throw new CustomException2();
}
}
}
@RunWith(MockitoJUnitRunner.class)
clas ATest{
@InjectMocks
private A a;
@Mock
private Helper helper;
// this is my test method which passes when ran individually. But will affect other tests if everything is ran same time.
@Test
public void testMethod() {
when(helper.method()).thenReturn("222");
String num = a.getNumber();
// doing this on purpose so I would land inside the catch. This line is causing issues.
Thread.currentThread().interrupt();
try {
assertEquals("222", num);
}catch (CustomException1 e){
// I will land here for this test as expected
// do some assertions
}
// Thread.currentThread().interrupt(); // Tried calling it again here to clear the flag but doesn't work.
}
// another few tests .....
}
Thread.interrupted()
方法来清除。Thread.currentThread().interrupt();
设置标志 - 它不会清除它。然而,我建议重新考虑设计,并使您的线程池可注入,并进一步将任务与执行器分离。 - Michał Krzywańskiinterrupt()
被注释掉),当此测试退出时,中断状态是清晰的。我怀疑问题只会在取消注释主题测试后的第二个interrupt()
调用时出现。 - erickson