JUnit @Test expected annotation not working

空扰寡人 提交于 2019-11-27 21:50:59

The problem was, that the class in which the test was nested was an extension of TestCase. Since this is JUnit 3 style, the annotation didn't work.

Now my test class is a class on its own.

@RunWith(JUnit4.class)
public class MyTestCaseBase extends TestCase 

I also had problems with @Test(expected = ...) annotation when I extended TestCase class in my base test. Using @RunWith(JUnit4.class) helped instantly (not an extremely elegant solution, I admit)

i tried this one, and work perfectly as expected.

public class SampleClassTest {
    @Test(expected = ArithmeticException.class )
    public void lost(){
        this.lost(0);
    }
    private void lost(int i) throws ArithmeticException {
        System.out.println(3/i);
    }
}

also ensure that junit4 is added as dependancy, @ (annotations) are new feature in junit 4.

I faced same issue, solution is simple "Don't extends TestCase class"

No, this JUnit test should work as it is - there is nothing more needed on this side.

What makes you sure that the test throws an IllegalStateException? Is it possible that it gets wrapped into another exception of different type?

Please post the exact failure message from JUnit.

As @duffymo suggested, it is easy to verify what (if any) exception the test really throws.

This looks correct to me.

Check your assumptions. Are you sure it throws the exception? If what you say is true, removing the expected from the annotation should make it fail.

I'd be stepping through the code with a debugger to see what's going on. I'll assume you have an IDE that will do so, like IntelliJ.

dhakre

I had the same problem I just changed my imports statements. I removed :

import org.junit.jupiter.api.Test;

import junit.framework.TestCase;

and added :

import org.junit.Test;

And it worked fine for me.

Just tested this under JUnit4: this DO work, test completes successfully. Look if it is a IllegalSelectorException or such.

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