【问题标题】:writing a JUnit Test case for custom checked exception in Java?为 Java 中的自定义检查异常编写 JUnit 测试用例?
【发布时间】:2013-12-18 15:42:39
【问题描述】:

我正在为我的类编写一个测试用例,其中包含抛出异常的方法(已检查和运行时)。正如link. 中所建议的那样,我尝试了不同的可能测试方法。看来它们似乎只适用于运行时异常。对于 Checked 异常,我需要执行 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);
    }

    }

测试类:

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

【问题讨论】:

    标签: java exception try-catch junit4 checked-exceptions


    【解决方案1】:
    @Test(expected = MyException.class)
    public void testMethod2() throws MyException {
        u.method2(9);
    }
    

    【讨论】:

    • 我有 @test(expected=MyException.class)` 装饰器时为什么要抛出 MyException
    • @user1988876 - 因为 java 编译器对 junit 注释及其含义一无所知。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2023-01-25
    相关资源
    最近更新 更多