简体   繁体   English

JUnit自定义注释

[英]JUnit custom annotation

I wanted to create a custom JUnit annotation, something similar to expected tag in @Test, but I want to also check the annotation message. 我想创建一个自定义的JUnit注释,类似于@Test中的预期标记,但我还要检查注释消息。

Any hints how to do that, or maybe there is something ready? 任何提示如何做到这一点,或者可能有一些准备好的东西?

JUnit 4.9 tightened up the library's use of "rules" for tests, which I think might work as well as a custom annotation. JUnit 4.9加强了图书馆对测试的“规则”的使用,我认为这可能与自定义注释一样有用。 Take a look at TestRule as a starting point. TestRule为出发点。 You can implement a rule based on that interface, and then use either the @ClassRule or (method-level) @Rule annotations to put them into play in your tests. 您可以基于该接口实现规则,然后使用@ClassRule或(方法级别)@Rule注释将它们放入测试中。

A good concrete example is ExpectedException , which lets you specify exceptions like the expected parameter for @Test does (and then some). 一个很好的具体示例是ExpectedException ,它允许您指定异常,例如@Test的预期参数(然后是一些)。

To make JUnit4 pickup your custom annotations, you need to write your own custom Runner implementation, and then supply that to the RunWith-annotation on the Test class. 要使JUnit4拾取您的自定义注释,您需要编写自己的自定义Runner实现,然后将其提供给Test类上的RunWith-annotation。

You can start out by having a look at the BlockJUnit4ClassRunner, which is the default implementation runner for JUnit 4 (if memory serves me well). 你可以先看看BlockJUnit4ClassRunner,它是JUnit 4的默认实现运行器(如果内存对我很好)。

Assuming you would want to pick up a custom annotation named @MyTest with a custom runner MyRunner, your test class would look something like: 假设您想要使用自定义运行器MyRunner选择名为@MyTest的自定义注释,您的测试类将类似于:

@RunWith(MyRunner.class)
class Tests {
   ...
   @MyTest
   public void assumeBehaviour() {
      ...
   }
}

The answer by "Reid Mac" does a fairly good job at decribing how a custom annotation is implemented. “Reid Mac”的答案在描述如何实现自定义注释方面做得相当不错。

You can create custom TestRule as mentioned in first answer or you can use/extend TestWatcher that already have method for processing start/finish of test. 您可以创建第一个答案中提到的自定义TestRule ,也可以使用/ extend TestWatcher ,它已经具有处理测试开始/结束的方法。 There is a method apply(Statement base, Description description) where description is actually a wrapper around your test method. 有一个方法apply(Statement base, Description description) ,其中描述实际上是测试方法的包装器。 Description has a great method getAnnotation(annotationClass) which will let you do what you want by specifying a custom annotation you want to process 说明有一个很好的方法getAnnotation(annotationClass) ,它可以通过指定要处理的自定义注释来执行所需的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM