Java 使用JUnit测试方法级别上是否存在自定义注释
我们有像这样的自定义注释Java 使用JUnit测试方法级别上是否存在自定义注释,java,rest,junit,Java,Rest,Junit,我们有像这样的自定义注释 @AuthTokenRequired(Permissions.SOME_PERMISSION) 或 我们在java代码中将其添加到某些REST端点 这看起来像这样: @Path("somePath") @Consumes("application/json") @Produces("application/json") public class SomeResource { @GET @AuthTokenRequired(Permissions.SOME_P
@AuthTokenRequired(Permissions.SOME_PERMISSION)
或
我们在java代码中将其添加到某些REST端点
这看起来像这样:
@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,但我们不希望这样做。您可以尝试以下方法:
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));
}
}
}
您可以尝试以下方法:
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));
}
}
}
请注意注释上的
RetentionPolicy
可能会破坏这一点哦,是的@RC。谢谢你指出这一点。为此,他需要一些解析器,比如javaparser
或类似的东西。注意注释上的RetentionPolicy
可能会破坏这一点哦,是的@RC。谢谢你指出这一点。为此,他需要一些解析器,比如javaparser
或类似的东西。