如何在每个JUnit @Test方法之前单独运行一些代码,而不使用@RunWith和AOP?

Łuk*_*man 4 java reflection junit aop

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

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

  1. @RunWith(我的测试可能,或者可能不会使用此注释,所以我不能假设我能够使用自己的跑步者)
  2. AOP(我不能对第三方库,例如AspectJ做任何依赖)

我想这只留给我反思,这对我很好.我想通过使用@Before并通过Thread.getCurrentThread()等获得当前的方法,但不知怎的,我觉得这个解决方案有点脏,因为我必须在这个方法中再次制作锅炉板代码来激发反射(和避免任何不必要的代码是首先的目标).

也许你有其他一些想法?

Mat*_*ell 11

基于TestRule,您需要一个非常类似于Mark单元测试答案的解决方案作为预期的故障.使用@Deprecated注释的示例(您可以在此处使用),如果方法上存在注释,则可以插入代码.Description类包含方法上的注释列表.

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
    }
}
Run Code Online (Sandbox Code Playgroud)