【问题标题】:How to run some code before each JUnit @Test method individually, without using @RunWith nor AOP?如何在每个 JUnit @Test 方法之前单独运行一些代码,而不使用 @RunWith 或 AOP?
【发布时间】:2012-01-04 06:06:51
【问题描述】:

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

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

  1. @RunWith(我的测试可能已经使用,也可能不使用这个注解,所以我不能假设我可以使用我自己的跑步者)
  2. AOP(我不能对第三方库建立任何依赖关系,例如 AspectJ)

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

也许您还有其他想法?

【问题讨论】:

  • 我不明白为什么不能使用@Before
  • 因为据我所知,Before 是在使用 Test 注释的每个方法之前运行的。我的预期行为是不同的。我希望我的自定义代码在标有 Mine 注释的方法上运行。它不能依赖于其他注解。
  • @Before 确实在每个方法之前运行。

标签: java reflection junit aop


【解决方案1】:

我会把班级分成两部分。一种是您使用@mine 注释的方法,另一种是其他方法。

然后照常使用@before。

这不会添加非标准代码,并且对于未来的开发人员也很容易理解和维护。

【讨论】:

    【解决方案2】:

    您需要一个与Mark unit test as an expected failure 的答案非常相似的解决方案,基于TestRule。使用 @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
        }
    }
    

    【讨论】:

    • 已确认。这按预期工作。我的最终解决方案是编写具有适当“@Rule”字段的抽象类。我的每个测试都扩展了这个类,所以剩下要做的就是随时使用我正确的“@Mine”注释。
    • 将内部类设为静态是否有害,即 public static class BeforeExecution implements TestRule
    • @Mr_and_Mrs_D 不,它没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2011-10-22
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多