如果在执行过程中抛出具体异常,将跳过测试的junit如何创建自己的注释? [英] How to create own annotation for junit that will skip test if concrete exception was thrown during execution?

查看:182
本文介绍了如果在执行过程中抛出具体异常,将跳过测试的junit如何创建自己的注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有几种执行模式,在1模式下,我的一些测试会抛出一个具体的异常是正常的。我需要使用类似@SkipOnFail的方法来注释这些方法,如果抛出异常,将把方法设置为跳过。

My application have several execution modes, and in 1 mode it is normal that some of my tests will throw a concrete exception. I need to annotate this methods with something like @SkipOnFail that will set method as skipped if exception was thrown.

提前感谢!

@Edit(我的问题要更清楚)

@Edit(for my question to be more clear)

@Test(expected=ConcreteException.class)

对我不起作用,因为即使没有抛出ConcreteException.class,我也需要传递测试(如果不抛出此异常,junit中的预期标记会将我的测试标记为失败),否则将被跳过。在所有其他情况下它应该一如既往。

does not work for me because i need my tests to pass even if ConcreteException.class was not thrown(expected tag in junit will mark my test as failed if this exception won't be thrown), and to be skipped otherwise. In all other cases it should work as always.

@Solution对我有用(junit v4.7)thx到@axtavt

@Solution that worked for me(junit v4.7) thx to @axtavt

@Rule
public MethodRule skipRule = new MethodRule() {
    public Statement apply(final Statement base, FrameworkMethod method, Object target) {
        if(method.getAnnotation(SkipOnFail.class) == null) return base;

        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try{
                    base.evaluate();
                } catch (ConcreteException e) {
                    Assume.assumeTrue(false);
                }
            }
        };
    }
};

@Thx

推荐答案

我不认为这样的功能是开箱即用的,但用自定义 TestRule 假设 ,如下所示:

I don't think that such a feature is available out of the box, but it should be pretty easy to implement with custom TestRule and Assume, something like this:

@Rule
public TestRule skipRule = new TestRule() {
    public Statement apply(final Statement base, Description desc) {
         if (desc.getAnnotation(SkipOnFail.class) == null) return base;

         return new Statement() {
             public void evaluate() throws Throwable {
                 try {
                     base.evaluate();
                 } catch (MyExceptoion ex) {
                     Assume.assumeTrue(false);
                 }
             }
         };
    }
};

这篇关于如果在执行过程中抛出具体异常,将跳过测试的junit如何创建自己的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆