如何在不使用@RunWith或AOP的情况下分别在每个JUnit @Test方法之前运行一些代码? [英] How to run some code before each JUnit @Test method individually, without using @RunWith nor AOP?

查看:479
本文介绍了如何在不使用@RunWith或AOP的情况下分别在每个JUnit @Test方法之前运行一些代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用例很简单:我想在JUnit test中的每个方法使用@Test 和我的自定义注释(我们将其称为@Mine)注释之前,先运行一些样板代码.

use case is simple: I want to run some boiler plate code before each method in JUnit test annotated with @Test and my custom annotation (let's call it @Mine).

我不想使用以下方法(括号中的解释):

I do not want to use following methods (explanation in parenthesis):

  1. @RunWith (我的测试可能会或可能不会已经使用此批注,因此我不能认为自己将能够使用自己的跑步程序)
  2. AOP (我不能依赖第三方库,例如AspectJ)
  1. @RunWith (my test may, or may not use this annotation already, so I cannot assume that I will be able to use my own runner)
  2. AOP (I cannot make any dependencies to third party libraries, such as AspectJ)

我想这只会让我产生反省,对我来说很好.我考虑过使用@Before并通过Thread.getCurrentThread()等获取当前方法,但是以某种方式我发现此解决方案有点脏,因为我必须在此方法中再次制作样板代码以触发反射(并且首先要避免任何不必要的代码.

I guess this leaves me with reflection only, which is fine by me. I thought off using @Before accompanied with getting current method via Thread.getCurrentThread() etc. but somehow I find this solution to be a little bit dirty, since I would have to make boiler plate code again within this method to fire reflection (and avoiding any unnecessary code was the goal in the first place).

也许您还有其他想法?

Maybe you have some other ideas?

推荐答案

您需要的解决方案与

You need a solution very similar to the answer to Mark unit test as an expected failure, based upon a TestRule. Using the example of a @Deprecated annotation (you can use yours here), you can insert code if the annotation exists on the method. The Description class contains the list of annotations on the method.

public class ExecutionTest {
    public class BeforeExecution implements TestRule {
        public Statement apply(Statement base, Description description) {
            return statement(base, description);
        }

        private Statement statement(final Statement base, final Description description) {
            return new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    if (description.getAnnotation(Deprecated.class) != null) {
                        // you can do whatever you like here.
                        System.err.println("this will be run when the method has an @Deprecated annotation");
                    }
                    base.evaluate();
                }
            };
        }
    }

    @Rule public BeforeExecution beforeExecution = new BeforeExecution();

    // Will have code executed.
    @Deprecated
    @Test public void test1() {
         // stuff
    }

    // won't have code executed.
    @Test public void test2() {
         // stuff
    }
}

这篇关于如何在不使用@RunWith或AOP的情况下分别在每个JUnit @Test方法之前运行一些代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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