JUnit Exception Testing: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 40: Line 40:


==Annotation Attributes==
==Annotation Attributes==
<syntaxhighlight lang='java'>
@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testSomething() {
  ...
}
</syntaxhighlight>

Revision as of 01:22, 29 January 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());
}

Annotation Attributes

@Test(expected = ArrayIndexOutOfBoundsException.class)
public void testSomething() {
  ...
}