Test expected exceptions with JUnit 3 and JUnit 4

With JUnit 4 it is pretty simple to test if an exception has been properly thrown because you can use annotations:

1
2
3
4
5
6
7
8
9
10
11
12
13
import static org.junit.Assert.fail;
import org.junit.*;
 
public class MyTestClass
{
 
  @Test(expected = NoMatchFoundException.class)
  public void testSomething() throws NoMatchFoundException
  {
    // Your critical code here!
    fail();
  }
}

If you are using JUnit 3 then it is not that easy because you don’t have annotations. That’s why you have to catch exceptions in the test code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import junit.framework.TestCase;
 
public class MyTestClass extends TestCase
{
  public void testSomething() throws NoMatchFoundException
  {
    try
    {
      // Your critical code here!
    }
    catch (NoMatchFoundException ex)
    {}
  }
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.