创建我自己的注释来扩展 JUnit4 行为
我一直在寻找有关如何使用我自己的注释扩展 JUnit4 的资源。
我希望能够定义一个 @ExpectedProblem
,我可以用它来标记我的一些测试。我看到网上似乎有一些关于如何扩展 TestNG 的材料,但我找不到任何可以扩展 JUnit4 的材料。
这里有人曾经扩展过 JUnit4 吗?
谢谢
I've been looking for resources on how to extend JUnit4 with my own annotations.
I'd like to be able to define a @ExpectedProblem
with which I could label some of my tests. I've seen there seems to be some material on the net on how to extend TestNG, but I could fine none to extend JUnit4.
Has anyone here extended JUnit4 in the past?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您希望
@ExpectedProblem
注释执行的操作,另一个选项是创建@Rule
。这需要 JUnit 4.7+,但应该比实现您自己的 Runner 更简单。
例如,如果您希望注释说“此测试应该抛出异常”,那么您需要查看
@ExpectedException
规则。即使这不足以满足您的需求,它也可以为实施您自己的规则提供一个良好的起点。Depending on what you want your
@ExpectedProblem
annotation to do, another option is to create a@Rule
.This requires JUnit 4.7+, but should be simpler than implementing your own
Runner
.For instance, if you want an annotation to say, "this test should throw an exception" then you'll want to take a look at the
@ExpectedException
rule. Even if that's not enough for your needs it can provide a good starting point for implementing your own rule.基本方法是创建您自己的类运行程序。例如,通过扩展
org.junit.runners.ParentRunner< /code>
或
org.junit.runners.BlockJUnit4ClassRunner
类。然后,您可以使用@RunWith(.class)
注释您的测试类。然后,在您的运行程序中,您可以分析测试类以检查注释并采取适当的操作等。找到此谷歌搜索:http://tedyoung.me/2011/01/23/junit-runtime-tests-custom-runners/这是Spring 如何使用
org.springframework.test.context.junit4.SpringJUnit4ClassRunner
Basic approach is to create your own class runner. For instance, by extending the
org.junit.runners.ParentRunner
ororg.junit.runners.BlockJUnit4ClassRunner
classes. You would then annotate your test class with@RunWith(<your class runner>.class)
. In your runner, you could then analyze the test-class to check for annotations and take appropriate actions etc. Found this googling: http://tedyoung.me/2011/01/23/junit-runtime-tests-custom-runners/This is how Spring modeled their JUnit support, using the
org.springframework.test.context.junit4.SpringJUnit4ClassRunner