有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Spring和Mockito模拟ContainerRequestContext?

我试图使用Mockito模拟ContainerRequestContext,但出现以下错误:

java.lang.ClassFormatError: Absent Code attribute in method
    that is not native or abstract in class file
    javax/ws/rs/core/Response

我的目标是在上下文中设置头来测试拦截器类

@RunWith(MockitoJUnitRunner.class) public class
MyInterceptorTest



@Mock
ContainerRequestContext context;

@Mock
MyService service;

@InjectMocks
MyInterceptor interceptor;



@Test
public void shouldAuthorizeUsingHEader() {
    when(context.getHeaderString("header1")).thenReturn("123456");
    when(context.getHeaderString("header2")).thenReturn("BigBall");

    interceptor.filter(context);

    verify(context, never()).abortWith(any(Response.class));
}

共 (2) 个答案

  1. # 1 楼答案

    试试这个
    而不是使用when().thenReturn()模拟模式, 试试doReturn().when()模拟模式

    例如,更改以下内容: when(context.getHeaderString("header1")).thenReturn("123456");

    为此: doReturn("123456").when(mockContext).getHeaderString("header1")

    还有, 在命名模拟对象时,请考虑使用前缀^ {< CD5> }。 在阅读少年读物时,它会有惊人的帮助 你写了六个月后

    我在Mkyong找到了一个不同的建议 确保在依赖项中使用了正确的javaee.jar。 再说一次,虽然不完全匹配

  2. # 2 楼答案

    只要删除或更新以下依赖项,一切正常:

         <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>6.0</version>
            <scope>provided</scope>
        </dependency>