Stefan Bollmann
Stefan Bollmann

Reputation: 720

How do I assert an IOException message with JUnit Test annotation?

When I use @Rule with ExpectedException as shown below in 1st (adapted post), I get the error "Unhandled Exception type" in the Class2testTest class at (*).

package class2test;

import java.io.IOException;

public class Class2test {
    public Class2test() throws IOException{
        throw new IOException("j");
    }
}

package test;

import java.io.IOException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import class2test.Class2test;

public class Class2testTest {

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

    @Test
    public void test() {
        expectedEx.expect(IOException.class);
        expectedEx.expectMessage("j");
        new Class2test(); //(*)
    }

}

I do not understand this: adapted post is reproducible (with a RuntimeException rather an IOException it works).

Upvotes: 1

Views: 2471

Answers (1)

tibtof
tibtof

Reputation: 7957

You should specify the thrown exception in the method's signature:

public void test() throws Exception {

Upvotes: 1

Related Questions