Showing posts with label junit. Show all posts
Showing posts with label junit. Show all posts

JUnit handle expected Exception

This code sample shows to handle expected exceptions. This requires JUnit 4.7+

import com.some.ClassUnderTest;

import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class TestClass {

    ClassUnderTest fixture;

    @Before
    public void setUp() throws Exception {

    }

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

    @Test
    public final void testCodeThatThrowsException() throws Exception {
  
        exception.expect(IllegalArgumentException.class);
        exception.expectMessage("Found illegal argument");
        fixture.methodThatThrowsException();
    }
}