简体   繁体   English

互斥注释

[英]Mutually exclusive annotations

Is it possible to mark two annotations as being mutually exclusive of each other? 是否可以将两个注释标记为互相排斥?

I've got a custom JUnit runner and I want to make sure that if a test is marked with my annotation @Custom marking it with @Test will throw (preferably) a compile error or (less preferably) a runtime error. 我有一个自定义的JUnit运行器,我想确保如果测试用我的注释标记@Custom@Test标记它将抛出(最好)编译错误或(不太优选)运行时错误。

The reason I want this is that @Custom is basically @Test but with some extra pre-processing before it runs the test. 我想要的原因是@Custom基本上是@Test但在运行测试之前有一些额外的预处理。 And, the way I've coded it, for each custom tag (yes, there's more than one), the test will be run as many times with the corresponding pre-processing each time. 而且,我编写它的方式,对于每个自定义标签(是的,不止一个),测试将每次运行多次并进行相应的预处理。 So, having it run for @Test as well doesn't make sense since that test is meant to have some pre-processing. 因此,让它运行@Test也没有意义,因为该测试意味着要进行一些预处理。

And, yes, I want to support both @Custom and @Test in my framework (although, not for the same test method). 而且,是的,我想在我的框架中同时支持@Custom@Test (尽管不是同一个测试方法)。

There isn't really any way to put limitations on what annotations you can put on a Java element. 实际上没有任何方法可以限制您可以在Java元素上添加的注释。 So, for example, you could mark a field as both @Required and @Optional , even though this would be completely nonsensical. 因此,例如,您可以将字段标记为@Required@Optional ,即使这完全是荒谬的。

You would have to do the check at runtime by looking at what annotations are present, or by looking for the specific one you are interested in, and then throwing an exception (which would be caught by a unit test). 您必须在运行时通过查看注释的位置,或者通过查找您感兴趣的特定注释,然后抛出异常(可以通过单元测试捕获)来进行检查。

There might be a better solution to your specific problem. 您的具体问题可能有更好的解决方案。 If you want to treat certain test cases specially, you might want to implement your own test runner and use the @RunWith annotation to invoke it. 如果您想特别处理某些测试用例,您可能希望实现自己的测试运行器并使用@RunWith批注来调用它。 Then, you could ensure your @Custom methods get the prerequisite actions. 然后,您可以确保您的@Custom方法获得先决条件操作。

You could utilize the Java Annotation Processing to do this for you (by calling a post-compile operation that in turn fails the compilation task), but it is needlessly complicated. 您可以利用Java Annotation Processing为您执行此操作(通过调用后编译操作,而后编译任务也会失败),但它不必要地复杂化。 (If you really want to, tell me and I dig out that code for you). (如果你真的想,请告诉我,我为你挖掘出代码)。 More easily it would be to have a small class that you call manually that collects the information. 更容易的是,您可以手动调用收集信息的小类。

So more precise: do you need it for you (yourself and only you) as convenience or do you need it for your huge project as an automated solution (and are willing to put some effort in it?) 更精确:你是否需要它(你自己和你自己)作为方便,或者你需要它作为一个自动化的解决方案(并愿意付出一些努力?)

由于代码在您的框架中运行,您可以添加AOP代码来检查互斥关系,方法是将pointCut添加到使用@Custom注释的所有类中,如果还有@Test注释,则抛出RuntimeException。

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

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