【发布时间】:2018-01-16 12:12:52
【问题描述】:
我正在尝试使用 Mockito 对使用 @NameBinding 应用的 ContainerRequestFilter 进行单元测试。过滤器检查注释字段以确定要做什么。 见示例代码:
注释
@Target({TYPE, METHOD})
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
MyEnum info() default MyEnum.DEFAULT;
}
我的枚举
public enum MyEnum {
VALUE1,
VALUE2,
DEFAULT
}
使用 MyEnum 作为条件的带注释的过滤器
@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)
}
}
}
带注释的资源方法
@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
}
}
这种设计可以很容易地在有新条件添加到过滤器时添加枚举值。
如何通过改变条件中的值对MyFilter 进行单元测试?
我尝试的一种方法是模拟ResourceInfo,然后在resourceInfo.getResourceMethod() 时返回模拟Method,但这无法完成,因为Method 是最终类。
同样不推荐模拟你不拥有的对象,那么有没有不同的方法来测试呢?我也不喜欢 Mockito,所以欢迎任何其他建议。
【问题讨论】:
标签: java unit-testing jersey jax-rs mockito