JUnit @Test期望注释不起作用

33 java junit annotations exception throwable

我有以下测试:

@Test(expected = IllegalStateException.class)
public void testKey() {
    int key = 1;
    this.finder(key);
}
Run Code Online (Sandbox Code Playgroud)

但是JUnit报告说,测试失败了,尽管它正如预期的那样抛出了IllegalStateException.

我是否必须配置其他内容才能运行?


我现在正在进行测试

@RunWith(Suite.class)
@SuiteClasses(Test.class)
public class TestSuite {

}
Run Code Online (Sandbox Code Playgroud)

就像在这个问题中,但仍然没有得到理想的结果.

当我删除test前缀时,我仍然收到错误.

我得说我用Eclipse运行这些测试,但它配置为使用JUnit 4 Runner.

小智 48

问题是,测试嵌套的类是扩展TestCase.由于这是JUnit 3样式,因此注释不起作用.

现在我的测试类本身就是一个类.


小智 9

@RunWith(JUnit4.class)
public class MyTestCaseBase extends TestCase 
Run Code Online (Sandbox Code Playgroud)

当我在基础测试中扩展TestCase类时,我也遇到了@Test(expected = ...)注释的问题.使用@RunWith(JUnit4.class)帮助即时(不是一个非常优雅的解决方案,我承认)


Dip*_*pak 7

我试过这个,并按预期完美地工作.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

还确保将junit4作为依赖项添加,@(注释)是junit 4中的新功能.


小智 6

我遇到同样的问题,解决方案很简单"不要扩展TestCase类"