Как проверить InterruptedException - PullRequest
       11

Как проверить InterruptedException

5 голосов
/ 25 сентября 2019

У меня есть следующий метод, который отлично работает.Я пытаюсь проверить сценарий, где выбрасывается InterruptedException.Вот как я сейчас тестирую, и это работает, если я только запускаю этот единственный тест.Но если бы я должен был выполнить все оставшиеся 5 тестов в своем тестовом классе, некоторые из них начинаются с ошибками.Все тесты проходят, когда я запускаю их по отдельности, поэтому, очевидно, мое прерывание Thread в тесте влияет на другие тесты.Как я могу написать свой тест так, чтобы он не влиял на другие тесты?

@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 ..... 
}

Ответы [ 2 ]

2 голосов
/ 25 сентября 2019

Я думаю, что лучший способ сделать это - смоделировать прерванное исключение

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

Но вы также можете просто сбросить флаг прерывания, вызвав метод:

Thread.interrupted()
1 голос
/ 25 сентября 2019

Вы должны симулировать, что ваш Future возвращает InterruptedException

Попробуйте это

@RunWith(MockitoJUnitRunner.class)
public class ATest {

@Test(expected = CustomException1.class)
public void testMethod() throws ExecutionException, InterruptedException {
    Future future = mock(Future.class);
    when(future.get()).thenThrow(new InterruptedException());
    A a = new A(future);

    a.getNumber();
}

// another few tests .....

}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...