1

I have to prevent using specific annotations in my project. Due to some specific circumstances, I have to prevent using org.junit.After annotation in project test classes. If anyone uses this annotation, whole tests logic will be violated.

It doesn't matter for me if it will happen during compilation or at runtime. My idea was to create aspect using Spring AOP which throws an exception on call After annotated method. Unfortunately, test classes are not Spring beans so AOP will not work here.

How can I do that? Is it possible to put some compilator directives which will prohibit using specific annotation?

2
  • Why do you need this? Commented Apr 7, 2018 at 10:51
  • @lexicore It's because same problem as here. I'm using selenium and I have to do screenshots on failed tests, but before 'After' logic. Following official JUnit statement and advice, I moved 'After' logic to different rule which call 'tearDown' method from base class. That's why I need to force users to override 'tearDown' method from base class instead of creating their own one with @After annotation. Commented Apr 7, 2018 at 11:05

1 Answer 1

0

You can write an AnnotationProcessor to generate error in complie period

Here is the annotation processor (find code on github):

@AutoService(Processor.class) @SupportedAnnotation(After.class) @SupportedSourceVersion(SourceVersion.RELEASE_8) public class Q49706464 extends XAbstractProcessor { @Override public boolean processActual(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws AssertException { roundEnv.getElementsAnnotatedWith(After.class) .forEach(e -> error().log("@After is banned.", e)); return false; } } 

For the following java file

import org.junit.After;

public class ForQ49706464 { @After public void after() { } } 

You will get following compile error

ForQ49706464.java:7: error: @After is banned. public void after() { ^ 

And you can integrate the annotation processor in your IDE to see the error message in text editor directly.

The XAbstractProcessor is from my library Annotation Processor Toolkit

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.