Junit 4.12 Issue testing exception

回眸只為那壹抹淺笑 提交于 2019-12-02 08:44:34

Just tested it, works as expected... The class...

public class SomeClass {

    public void someMethod(String someParameter) throws SomeException {
        throw new SomeException("Yep, really a SomeException");
    }

}

The exception...

public class SomeException extends Exception {

    public SomeException(String message) {
        super(message);
    }

}

And the test class, both tests work exactly as expected:

public class TestSomeClass {

    @Rule
    public ExpectedException exception = ExpectedException.none();

    @Test
    public void testSomeMethodWithRule() throws SomeException {
        exception.expect(SomeException.class);

        new SomeClass().someMethod("something");
    }

    @Test(expected=SomeException.class)
    public void testSomeMethodWithExpected() throws SomeException { 
        new SomeClass().someMethod("something");
    }
}

After downloading your project (see comment), I don't know for sure why, but I know what the problem is: It's the extends Testcase. I assume that this somehow leads to a different way of executing your unit tests (stacktrace implies that they get executed with the JUnit38ClassRunner then). Remove it (you don't need it anyway) and instead call your asserts with Assert.<something>, for example Assert.assertTrue(...). (You can use static imports for that, too, so you don't have to write the Assert part). That solves your problem and all tests succeed.

Another possibility seems to be to keep the extends TestCase and use @RunWith(BlockJUnit4ClassRunner.class), which also fixes your problem, so probably the default Runner for a TestCase isn't up to it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!