JUnit Exception Testing: Difference between revisions
Jump to navigation
Jump to search
(Created page with "=Internal= * JUnit") |
|||
(7 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=External= | |||
* https://github.com/junit-team/junit4/wiki/Exception-testing | |||
=Internal= | =Internal= | ||
* [[JUnit#Patterns|JUnit]] | * [[JUnit#Patterns|JUnit]] | ||
=Idioms= | |||
==Try/Catch== | |||
<syntaxhighlight lang='java'> | |||
try { | |||
... | |||
fail("should have thrown exception"); | |||
} | |||
catch(SomeException e) { | |||
assertEquals("some message", e.getMessage()); | |||
} | |||
</syntaxhighlight> | |||
==assertThrows()== | |||
<syntaxhighlight lang='java'> | |||
@Test | |||
public void testExceptionAndState() { | |||
List<Object> list = new ArrayList<>(); | |||
IndexOutOfBoundsException thrown = assertThrows( | |||
IndexOutOfBoundsException.class, | |||
() -> list.add(1, new Object())); | |||
// assertions on the thrown exception | |||
assertEquals("Index: 1, Size: 0", thrown.getMessage()); | |||
// assertions on the state of a domain object after the exception has been thrown | |||
assertTrue(list.isEmpty()); | |||
} | |||
</syntaxhighlight> | |||
==<span id='Annotation_Attributes'></span>@Test Annotation 'expected' Attribute== | |||
<syntaxhighlight lang='java'> | |||
@Test(expected = ArrayIndexOutOfBoundsException.class) | |||
public void testSomething() { | |||
... | |||
} | |||
</syntaxhighlight> |
Latest revision as of 17:06, 16 July 2021
External
Internal
Idioms
Try/Catch
try {
...
fail("should have thrown exception");
}
catch(SomeException e) {
assertEquals("some message", e.getMessage());
}
assertThrows()
@Test
public void testExceptionAndState() {
List<Object> list = new ArrayList<>();
IndexOutOfBoundsException thrown = assertThrows(
IndexOutOfBoundsException.class,
() -> list.add(1, new Object()));
// assertions on the thrown exception
assertEquals("Index: 1, Size: 0", thrown.getMessage());
// assertions on the state of a domain object after the exception has been thrown
assertTrue(list.isEmpty());
}
@Test Annotation 'expected' Attribute
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testSomething() {
...
}