JUNIT - 断言异常
JUNIT - Asserting Exceptions
我正在使用 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();
}
}
以下代码是使用异常规则的最小示例。
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();
}
}
使用规则的另一种方法(并且更简单?)是在您希望发生异常的调用之后放置一个 fail()。如果您遇到异常,则测试方法成功(您永远不会失败)。如果你没有得到异常并且你到达了 fail() 语句,那么测试失败。
我正在使用 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();
}
}
以下代码是使用异常规则的最小示例。
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();
}
}
使用规则的另一种方法(并且更简单?)是在您希望发生异常的调用之后放置一个 fail()。如果您遇到异常,则测试方法成功(您永远不会失败)。如果你没有得到异常并且你到达了 fail() 语句,那么测试失败。