How to handle exceptions while unit testing using JUnit?

谁说我不能喝 提交于 2019-12-14 01:25:58

问题


If a method throwing an exception, how to write a test case to verify that method is actually throwing the expected exception?


回答1:


You can try and catch the desired exception and do something like assertTrue(true):

@Test
testIfThrowsException(){
    try{
        funcThatShouldThrowException(arg1, agr2, agr3);
        assertTrue("Exception wasn't thrown", false);
    }
    catch(DesiredException de){
        assertTrue(true);
    }
}



回答2:


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?");
        }
 }



回答3:


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.



来源:https://stackoverflow.com/questions/12184281/how-to-handle-exceptions-while-unit-testing-using-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!