Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - How to create own annotation for junit that will skip test if concrete exception was thrown during execution?

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.

thanks in advance!

@Edit(for my question to be more clear)

@Test(expected=ConcreteException.class)

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 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...