3

メソッドが例外をスローする場合、そのメソッドが実際に予期された例外をスローしていることを確認するためのテストケースを作成するにはどうすればよいですか?

4

3 に答える 3

12

In newest versions of JUnit it works that way:

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

public class NumberFormatterExceptionsTests {

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

    @Test
    public void shouldThrowExceptionWhenDecimalDigitsNumberIsBelowZero() {
        thrown.expect(IllegalArgumentException.class); // you declare specific exception here
        NumberFormatter.formatDoubleUsingStringBuilder(6.9, -1);
    }
}

more on ExpectedExceptions:

http://kentbeck.github.com/junit/javadoc/4.10/org/junit/rules/ExpectedException.html

http://alexruiz.developerblogs.com/?p=1530

// These tests all pass.
 public static class HasExpectedException {
        @Rule
        public ExpectedException thrown= ExpectedException.none();

        @Test
        public void throwsNothing() {
    // no exception expected, none thrown: passes.
        }

        @Test
        public void throwsNullPointerException() {
                thrown.expect(NullPointerException.class);
                throw new NullPointerException();
        }

        @Test
        public void throwsNullPointerExceptionWithMessage() {
                thrown.expect(NullPointerException.class);
                thrown.expectMessage("happened?");
                thrown.expectMessage(startsWith("What"));
                throw new NullPointerException("What happened?");
        }
 }
于 2012-08-29T18:32:15.140 に答える
5

Two options that I know of.

If using junit4

@Test(expected = Exception.class)

or if using junit3

try {
    methodThatThrows();
    fail("this method should throw excpetion Exception");
catch (Exception expect){}

Both of these catch Exception. I would recommend catching the exception you are looking for rather than a generic one.

于 2012-08-29T18:32:47.697 に答える
0

目的の例外をキャッチして、次のようなことを行うことができますassertTrue(true)

@Test
testIfThrowsException(){
    try{
        funcThatShouldThrowException(arg1, agr2, agr3);
        assertTrue("Exception wasn't thrown", false);
    }
    catch(DesiredException de){
        assertTrue(true);
    }
}
于 2012-08-29T18:30:14.010 に答える