为 Java 中的自定义检查异常编写 JUnit 测试用例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20336657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:09:43  来源:igfitidea点击:

writing a JUnit Test case for custom checked exception in Java?

javaexceptiontry-catchjunit4checked-exceptions

提问by brain storm

I am writing a test case for my class that has methods which throw exceptions (both checked and runtime). I have tried different possible ways of testing as suggested in this link.. It appears they seem to work only for runtime exceptions. for Checked exceptions, I need to do a try/catch/assert as shown in the code below. Is there any alternatives to try/catch/assert/. you will notice that testmethod2() and testmethod2_1()shows compile error but testmethod2_2()does not show compile error which uses try/catch.

我正在为我的类编写一个测试用例,其中包含抛出异常(检查和运行时)的方法。我已经按照此链接中的建议尝试了不同的可能测试方法. 看起来它们似乎只适用于运行时异常。对于已检查的异常,我需要执行 try/catch/assert,如下面的代码所示。是否有任何替代 try/catch/assert/. 您会注意到testmethod2() and testmethod2_1()显示编译错误但testmethod2_2()不显示使用 try/catch 的编译错误。

class MyException extends Exception {

    public MyException(String message){
        super(message);
    }
}


public class UsualStuff {

    public void method1(int i) throws IllegalArgumentException{
        if (i<0)
           throw new IllegalArgumentException("value cannot be negative");
        System.out.println("The positive value is " + i );
    }

    public void method2(int i) throws MyException {
        if (i<10)
            throw new MyException("value is less than 10");
        System.out.println("The value is "+ i);
    }

    }

Test class:

测试类:

import static org.junit.Assert.*;

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


public class UsualStuffTest {

    private UsualStuff u;

    @Before
    public void setUp() throws Exception {
        u = new UsualStuff();
    }

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

    @Test(expected = IllegalArgumentException.class)
    public void testMethod1() {
        u.method1(-1);
    }

    @Test(expected = MyException.class)
    public void testMethod2() {
        u.method2(9);
    }

    @Test
    public void testMethod2_1(){
        exception.expect(MyException.class);
        u.method2(3);
    }

    public void testMethod2_3(){
        try {
            u.method2(5);
        } catch (MyException e) {
            assertEquals(e.getMessage(), "value is less than 10") ;
        }
    }
}

采纳答案by jtahlborn

@Test(expected = MyException.class)
public void testMethod2() throws MyException {
    u.method2(9);
}