Exception testing
12149 단어 exception
Exception testing
Expected Exceptions
How do you verify that code throws exceptions as expected? Verifying that code completes normally is important, but making sure the code behaves as expected in exceptional situations is vital too. For example:
new ArrayList<Object>().get(0);
This code should throw an IndexOutOfBoundsException. The
@Test
annotation has an optional parameter "expected
"that takes as values subclasses of Throwable
. If we wanted to verify that ArrayList
throws the correct exception, we would write: @Test(expected= IndexOutOfBoundsException.class)
public void empty() {
new ArrayList<Object>().get(0);
}
The
expected
parameter should be used with care. The above test will pass if any code in the method throws IndexOutOfBoundsException
. For longer tests, it's recommended to use the ExpectedException
rule, which is described below. Deeper Testing of the Exception
The above approach is useful for simple cases, but it has its limits. For example, you can't test the value of the message in the exception, or the state of a domain object after the exception has been thrown.
Try/Catch Idiom
To address this you can use the try/catch idiom which prevailed in JUnit 3.x:
@Test
public void testExceptionMessage() {
try {
new ArrayList<Object>().get(0);
fail("Expected an IndexOutOfBoundsException to be thrown");
} catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
}
}
ExpectedException Rule
Alternatively, use the
ExpectedException
rule. This rule lets you indicate not only what exception you are expecting, but also the exception message you are expecting: @Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void shouldTestExceptionMessage() throws IndexOutOfBoundsException {
List<Object> list = new ArrayList<Object>();
thrown.expect(IndexOutOfBoundsException.class);
thrown.expectMessage("Index: 0, Size: 0");
list.get(0); // execution will never get past this line
}
The expectMessage also lets you use Matchers, which gives you a bit more flexibility in your tests. An example:
thrown.expectMessage(JUnitMatchers.containsString("Size: 0"));
For an expanded discussion of the
ExpectedException
rule, see this blog post .
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Exception Class에서 에러 코드 해석 ~초기초편~직장에서 C# 프로젝트가 내뿜는 오류 코드를 구문 분석하고 오류의 위치를 확인하기 위해 Exception class를 활용할 수 있었습니다. 지금까지 Exception Class 에 대해서 별로 파악할 수 없었기 때...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.