java JUnit 自定义注解

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7921504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:02:16  来源:igfitidea点击:

JUnit custom annotation

javajunitannotations

提问by Szymon Lipiński

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?

任何提示如何做到这一点,或者可能已经准备好了?

采纳答案by bhavanki

JUnit 4.9 tightened up the library's use of "rules" for tests, which I think might work as well as a custom annotation. Take a look at TestRuleas a starting point. 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.

JUnit 4.9 加强了库对测试“规则”的使用,我认为这可能与自定义注释一样有效。以TestRule为起点。您可以基于该接口实现规则,然后使用 @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 的预期参数那样的异常(然后是一些)。

回答by Anders

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”的回答在描述如何实现自定义注释方面做得相当好。

回答by dev_il

You can create custom TestRuleas mentioned in first answer or you can use/extend TestWatcherthat already have method for processing start/finish of test. There is a method apply(Statement base, Description description)where description is actually a wrapper around your test method. Descriptionhas a great method getAnnotation(annotationClass)which will let you do what you want by specifying a custom annotation you want to process

您可以创建第一个答案中提到的自定义TestRule,或者您可以使用/扩展已经具有处理测试开始/结束方法的TestWatcher。有一种方法apply(Statement base, Description description),其中描述实际上是测试方法的包装器。Description有一个很棒的方法getAnnotation(annotationClass),它可以让您通过指定要处理的自定义注释来做您想做的事