使用JUnit

时间:2017-11-03 10:08:26

标签: java rest junit

我们有自定义注释,如

@AuthTokenRequired(Permissions.SOME_PERMISSION)

@ClientAppKeyRequired

我们在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
  }
}

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

我们正在使用JUnit4,MockitoJunit和Hamcrest进行断言。也有可能使用Powermock,但我们不愿意。

1 个答案:

答案 0 :(得分:2)

您可以尝试以下内容:

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));
        }
    }
}