首页 文章

使用@Test注释在Junit Test中期望异常或其子类之一

提问于
浏览
8

我有一个期望特定异常的测试,例如:

@Test(expected=MyException.class)
public void testMyMethod(){
    myMethod();
}

myMethod() 方法实际上抛出 MyException 的子类,让我们称之为 MySubclassException .

Is there anyway to define my test using the @Test annotation to accept subclasses of MyException as well as the class itself?

我知道我可以自己编写测试检查逻辑而不使用 expected 捕获异常并设置标志,但我想知道JUnit是否已经支持匹配异常子类 .

3 回答

  • 3

    这已经由框架为您处理

    让我们举一个小例子(非常糟糕的代码):import static org.junit.Assert . *;

    import org.junit.Test;
    
    
    public class TestExpect {
    
    @Test(expected=MyException.class)
    public void test() throws MyException {
        new Foo().foo();
    }
    
    }
    

    有两个异常类MyException和MyExtendedException从前一个继承而且一个简单的Foo类如下:

    public class Foo {
    
    public void foo() throws MyException{
        throw new MyExtendedException();
    }
    }
    

    使用Eclipse运行器启动测试会打印一个绿色条,因为测试会引发一个Myexception实例(是POO中的关系)

    如果您更喜欢阅读源代码,那么这是Junit源代码(ExpectException.java)的一个exxcerpt:

    @Override
        public void evaluate() throws Exception {
            boolean complete = false;
            try {
                fNext.evaluate();
                complete = true;
            } catch (AssumptionViolatedException e) {
                throw e;
            } catch (Throwable e) {
                if (!fExpected.isAssignableFrom(e.getClass())) {
                    String message= "Unexpected exception, expected<"
                                + fExpected.getName() + "> but was<"
                                + e.getClass().getName() + ">";
                    throw new Exception(message, e);
                }
            }
            if (complete)
                throw new AssertionError("Expected exception: "
                        + fExpected.getName());
        }
    
  • 0

    如果 myMethod() 抛出 MyExceptionMySubclassException ,则测试将通过 . 我用这段代码测试了这个概念:

    public class ExceptionTest {
    
        private static class ExceptionA extends Exception {
    
        }
    
        private static class ExceptionB extends ExceptionA {
    
        }
    
        @Test(expected=ExceptionA.class)
        public void test() throws Exception {
            throw new ExceptionB();
        }
    }
    
  • 3

    具有Catch异常的

    BDD样式解决方案

    @Test
    public void testMyMethod() {
    
        when(foo).myMethod();
    
        then(caughtException()).isInstanceOf(MyException.class);
    
    }
    

    依赖关系

    com.googlecode.catch-exception:catch-exception:1.2.0
    

相关问题