Search code examples
eclipsejunitrulesexpected-exception

ExpectedException with @Rule in junit test on eclipse IDE does not work


I need to make a test in junit that passes if an exception is thrown, but fail time and again.

I read a bunch of questions and answers on the topic here in stackoverflow and on other sources. Eventually I came across this page, that explains the usage of Class ExpectedException, by junit.org.

Since I could not get my own test working I copied their bare-bones example and it still did not work.

here is my code:

import static org.junit.jupiter.api.Assertions.*;

import org.junit.Rule;
import org.junit.jupiter.api.Test;
import org.junit.rules.ExpectedException;

class AssertExceptionTest {
    
    @Rule
    public ExpectedException thrown= ExpectedException.none();

    @Test
    public void throwsNothing() {
        // no exception expected, none thrown: passes.
    }

    @Test
    public void throwsExceptionWithSpecificType() {
        thrown.expect(NullPointerException.class);
        throw new NullPointerException();
    }
}

Citing from the page I mentioned above, the explanation goes "...After specifiying the type of the expected exception your test is successful when such an exception is thrown and it fails if a different or no exception is thrown...

Problem is that the test still fails, no matter what I do, and it fails because of what I am trying to verify: throwing NullPointerException.

I thought that maybe, because I am using junit 5, my test fails. However, this question from stackoverflow suggests otherwise: the guy asking the question mentions he is using junit 5 in eclipse the same way as in my code, successfully.

Technical details: eclipse version: 2019-12 (4.14.0) junit version: junit 5 working on Ubuntu, version: 18.04.2 LTS.

Update: I used assertThrows(), and it worked for me. However, I am still puzzled over the reason I didn't succeed with the methods described above, which many people here suggest.

Thanks in advance!


Solution

  • JUnit 5 does not support JUnit 4 Rules out of the box.

    To make your code working:

    1. Add the following dependency (version might change over time, of course)
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-migrationsupport</artifactId>
        <version>5.5.2</version> 
        <scope>test</scope>
    </dependency>
    
    1. Next, put @EnableRuleMigrationSupport on top of your test class.

    That's it. See this for more information.