gpt4 book ai didi

java - 如何测试 InterruptedException

转载 作者:搜寻专家 更新时间:2023-10-31 20:16:36 39 4
gpt4 key购买 nike

我有以下方法,效果很好。我正在尝试测试抛出 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 .....
}

最佳答案

我认为最好的方法是模拟中断的异常

when(helper.method())).thenThrow(InterruptedException.class);

但是你也可以通过调用方法清除中断标志:

Thread.interrupted()

关于java - 如何测试 InterruptedException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58105040/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com