简体   繁体   English

Java注释可以进行单元测试吗?

[英]Can Java annotations be unit tested?

I've recently started creating my own annotations and to sport TDD/BDD, I'd want to unit test my annotations to create a clear specification for them. 我最近开始创建自己的注释并运行TDD / BDD,我想要对我的注释进行单元测试,以便为它们创建一个明确的规范。 However since annotations are basically merely fancy interfaces which to my knowledge can't be really instantiated directly, is there any way short of reflection to unit test an annotation? 然而,由于注释基本上只是花哨的界面,据我所知,这些界面无法直接实例化,是否有任何方法缺乏反映单元测试注释?

Annotations have some impact (otherwise, it would be pointless to use them). 注释会产生一些影响(否则,使用它们将毫无意义)。 So don't test the annotation presence but the effect it should have. 因此,不要测试注释存在,但应测试它应具有的效果。

It's not something I would usually write tests for, but you could simply create a set of test classes which use and abuse the annotation, to test that it is storing its member values, that it has the correct defaults etc. 这不是我通常会编写测试的东西,但你可以简单地创建一组使用和滥用注释的测试类,测试它是否存储其成员值,它是否具有正确的默认值等。

This will only work on Runtime annotations that are specfied on the correct targets of course. 这仅适用于在正确的目标上指定的运行时注释。

In my experience, annotations themselves are rarely interesting enough to warrant unit tests - it is usually the code which uses them that needs testing. 根据我的经验,注释本身很少有趣,足以保证单元测试 - 通常是使用它们需要测试的代码。 But then I'm not from the 100% code coverage school of thought :-) 但后来我不是来自100%代码覆盖的思想学校:-)

You can unit test if your annotation definition is ok: can it be applied to the valid set of elements, is it available at runtime if required, does the default value correctly initialized? 如果注释定义正常,则可以进行单元测试:它是否可以应用于有效的元素集,是否在运行时可用(如果需要),是否正确初始化了默认值? Then, later on, unit test the class that will process your annotation. 然后,稍后,单元测试将处理您的注释的类。

You can't test them directly since, as you noted, there's nothing there to test. 你无法直接测试它们,因为正如你所指出的那样,没有什么可以测试的。 You could prove some things, though: 但你可以证明一些事情:

  • Objects with annotations in the code have any expected annotations at runtime 代码中带注释的对象在运行时具有任何预期的注释
  • Default values have been initialized 默认值已初始化
  • The annotations bind to the things you expect them to 注释绑定到您期望它们的内容

When you unit test, one of the things you can prove is that your implementation conforms to the interface. 在进行单元测试时,您可以证明的一点是您的实现符合接口。 So if an annotation implies certain behavior or properties (eg Serializable things really should be serializable), you would want to represent this in your tests, too. 因此,如果注释暗示某些行为或属性(例如Serializable事物确实应该是可序列化的),那么您也希望在测试中表示这一点。

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

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