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.

0

1 Answer 1

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));
        }
    }
}   
Sign up to request clarification or add additional context in comments.

2 Comments

Note that RetentionPolicy on the annotation could break that
Oh yes @RC. Thanks for pointing that out. For that he will need some parser like javaparser or similar stuff.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.