2

We have custom annotations like

@AuthTokenRequired(Permissions.SOME_PERMISSION)

or

@ClientAppKeyRequired

which we add to certain REST-Endpoints in our java code.

This looks something like this:

@Path("somePath")
@Consumes("application/json")
@Produces("application/json")
public class SomeResource {

  @GET
  @AuthTokenRequired(Permissions.SOME_PERMISSION)
  @ClientAppKeyRequired
  public Response getSomeData(){
    //some code
  }

  @GET
  @ClientAppKeyRequired
  public Response getSomeOtherData(){
    //some code
  }

  @DELETE
  @AuthTokenRequired(Permissions.SOME_PERMISSION)
  public Response deleteSomeData(){
    //some code
  }
}

What we want to test is if these endpoints are annotated correctly on method level.

We are using JUnit4, MockitoJunit and Hamcrest for assertions. There is also a possibility to use Powermock but we would prefer not to.

CodeChimpy
  • 560
  • 1
  • 6
  • 26

1 Answers1

6

You can try something like :

import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Test;

public class SomeResourceHasAnnotatedField {

    @Test
    public void testHasMethodsWithAnnotation() throws SecurityException, NoSuchMethodException {
        Class resourceClass = SomeResource.class;
        Method[] methods = resourceClass.getDeclaredMethods();
        for (Method m : methods) {
            Assert.assertNotNull("Method :"+m.getName() + " does not have annotation AuthTokenRequired",m.getAnnotation(AuthTokenRequired.class));
            Assert.assertNotNull("Method :"+m.getName() + " does not have annotation ClientAppKeyRequired",m.getAnnotation(ClientAppKeyRequired.class));
        }
    }
}   
Optional
  • 4,387
  • 4
  • 27
  • 45
  • 1
    Note that `RetentionPolicy` on the annotation could break that –  Nov 03 '17 at 10:28
  • Oh yes @RC. Thanks for pointing that out. For that he will need some parser like `javaparser` or similar stuff. – Optional Nov 03 '17 at 10:48