Unit testing ContainerRequestFilter which uses ResourceInfo with mockito

Viewed 5434

I'm trying to use Mockito to unit test a ContainerRequestFilter, which is applied using @NameBinding. The filter checks an annotation field to determine what to do. See sample code:

Annotation

@Target({TYPE, METHOD})
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    MyEnum info() default MyEnum.DEFAULT;
}

MyEnum

public enum MyEnum {
    VALUE1,
    VALUE2,
    DEFAULT
}

Annotated Filter which uses MyEnum as conditional

@MyAnnotation
public class MyFilter implements ContainerRequestFilter {

    @Context
    private ResourceInfo resourceInfo;

    @Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {

        if (resourceInfo.getResourceMethod().getAnnotation(MyAnnotation.class).info().equals(MyEnum.VALUE1)) 
        {
            // set some value or throw some exception (this can be verified in the test)
        }

        if (resourceInfo.getResourceMethod().getAnnotation(MyAnnotation.class).info().equals(MyEnum.VALUE2))
        {
           // set some value or throw some exception (this can be verified in the test)
        }
    }
}

Annotated Resource methods

@Path("/somepath1")
public class MyResource1
{
    @GET
    @MyAnnotation(info = MyEnum.VALUE1)
    public Response someResourceMethod()
    {
        // return response
    } 
}


@Path("/somepath2")
public class MyResource2
{
    @GET
    @MyAnnotation(info = MyEnum.VALUE2)
    public Response someResourceMethod()
    {
        // return response
    } 
}

This design makes it easy to just add enum values when there are new conditions to be added to the filter.

How can I unit test MyFilter, by varying the values in the conditional?

One approach I tried was to mock ResourceInfo and then return mock Method when resourceInfo.getResourceMethod(), but this cannot be done since Method is a final class.

Also mocking objects you don't own is not recommended, so is there a different approach to test this? I am also not wedded to Mockito, so open to any other suggestions.

1 Answers
Related