How can I test exceptions using Test Driven Design concept in eclipse

82 views Asked by At

I'm writing a Stack class using the Test Driven Design concept.

In the setUp() method my stack is created with 0 elements like this

Stack stack = new Stack();

This is my attempted test to catch the StackEmptyException which would be raised when top is immediately called after setUp().

@Test
public final void testTopIsEmpty() throws StackEmptyException
{
  StackEmptyException thrown = null;
  try
  {
    stack.top();
  }
  catch (StackEmptyException caught)
  {
    thrown = caught;
  }
  assertThat(thrown, is(instanceOf(StackEmptyException.class)));
}

My problem is in the last line. I don't understand why my code doesn't work!

2

There are 2 answers

4
Adam On

The correct way to test for an exception in JUnit is:

@Test(expected = StackEmptyException.class)
public final void testTopIsEmpty() throws Exception
{
    stack.top();
}
2
fgb On

ExpectedException can be used to verify that an exception is thrown. The check can be in the middle of a method to make sure earlier method calls don't accidentally throw the same exception.

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

@Test
public void testTopIsEmpty() throws StackEmptyException {
    thrown.expect(StackEmptyException.class);
    stack.top();
}