Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test InterruptedException

Tags:

java

I have the following method which works fine. I am trying to test the scenario where an InterruptedException is thrown. This is how I am testing currently which works if I only run this single test. But if I were to run all remaining 5 tests in my test class, some starts failing. All tests passes when I run them individually thus clearly my Thread interrupt in the test is affecting other tests. How can I write my test in a way it won't affect other tests?

@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 ..... 
}
like image 287
karvai Avatar asked Oct 28 '22 08:10

karvai


1 Answers

I think the best way to do that is to Mock the interrupted exception

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

But you can also just clear the interruption flag by calling the method:

Thread.interrupted()
like image 95
Cλstor Avatar answered Nov 14 '22 16:11

Cλstor