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. 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?
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 (e.g. Serializable
things really should be serializable), you would want to represent this in your tests, too.
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.
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 :-)