使用 JUnit 测试方法级别是否存在自定义注释

Cod*_*mpy 2 java rest junit

我们有自定义注释,例如

@AuthTokenRequired(Permissions.SOME_PERMISSION)
Run Code Online (Sandbox Code Playgroud)

或者

@ClientAppKeyRequired
Run Code Online (Sandbox Code Playgroud)

我们将其添加到 java 代码中的某些 REST-Endpoints 中。

这看起来像这样:

@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
  }
}
Run Code Online (Sandbox Code Playgroud)

我们想要测试的是这些端点是否在方法级别上正确注释。

我们使用 JUnit4、MockitoJunit 和 Hamcrest 进行断言。也可以使用 Powermock,但我们不想这样做。

Opt*_*nal 6

你可以尝试这样的事情:

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));
        }
    }
}   
Run Code Online (Sandbox Code Playgroud)