Search code examples
groovyannotationstddspock

Spock: test that a Groovy class has a certain annotation?


For example, any way to test that a given Groovy class has the annotation @Slf4j?

This is in a TDD context: I don't want to add an annotation until I can see a failing test.


Solution

  • The @Slf4j annotation has @Retention(SOURCE). So the annotation information is not available at runtime. This makes testing almost impossible. You could read the source file and parse it in the test and cheeck that there is a @Slf4j annotation.

    Having an annotation with @Retention(RUNTIME) would change the picture:

    class AnnotationSpec extends Specification{
    
        void "test that class has annotation"() {
            given:
            def annotation = ShouldHaveAnnotation.class.getAnnotation(ClassAnnotation)
    
            expect:
            annotation != null
        }
    }
    
    @Target([TYPE])
    @Retention(RetentionPolicy.RUNTIME)
    @interface ClassAnnotation{
    
    }
    
    @ClassAnnotation
    class ShouldHaveAnnotation {
    
    }
    

    So far for the fact based answer.

    My thoughts on TDD:

    What is the meaning of your test use case? Do you just want to follow TDD blindly?

    Every so called software craftmenship workflow is motivated by the assumption that software development relates to 1800 century furniture manufacturing. I know how to build furniture and dove tails is the strongest joint, looks great, but very expensive. A biscuit joint is modern, doesn't look that nice but is strong as well and cheap. So I decide on base of my experience whether to go for dove tails or modern biscuit joints.

    I usually don't test stuff, that don't cause trouble. How do I know, .. well experience. Just use a @CompileStatic annotation on your class and the compiler will catch a missing log instance or just write a test that calls a method that uses a logger.

    One mark on TDD as a source for good design: TDD creates good micro software design, but ignores macro design and that's the most important part of the software.