JUNIT - 断言例外

时间:2016-09-27 16:06:26

标签: java junit junit4

我正在使用JUNIT 4.我试图使用下面的代码断言异常,但它没有用。

@Rule
public ExpectedException thrown = ExpectedException.none();
thrown.expect(ApplicationException.class);

然而,当我使用下面的注释时,它工作并且测试通过了。

@Test(expected=ApplicationException.class)

如果我错过了什么,请告诉我。

import org.junit.Rule;
import org.junit.rules.ExpectedException;

public class Test
{

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

    @org.junit.Test
    public void throwsIllegalArgumentExceptionIfIconIsNull()
    {


        exception.expect(IllegalArgumentException.class);
        toTest();
    }

    private void toTest()
    {
        throw new IllegalArgumentException();
    }
}

2 个答案:

答案 0 :(得分:2)

以下代码是使用例外规则的最小示例。

public class Test
{

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

    @org.junit.Test
    public void throwsIllegalArgumentExceptionIfIconIsNull()
    {
        exception.expect(IllegalArgumentException.class);
        toTest();
    }

    private void toTest()
    {
        throw new IllegalArgumentException();
    }
}

另请参阅(Wiki entry about rules)

答案 1 :(得分:1)

使用规则的另一种方法(更简单?)是在您希望发生异常的调用之后放置fail()。如果您获得异常,则测试方法成功(您永远不会达到失败)。如果你没有得到异常而你到达fail()语句,则测试失败。

相关问题