【问题标题】:How to Mock ContainerRequestContext using Spring and Mockito?如何使用 Spring 和 Mockito 模拟 ContainerRequestContext?
【发布时间】:2018-06-19 17:59:33
【问题描述】:

我正在尝试使用 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));
}

【问题讨论】:

  • 提供一些代码示例。我只能假设您只是以这种方式模拟它: ContainerRequestContext requestContext = mock(ContainerRequestContext.class);并抛出 ClassFormatError。
  • 更新了@MeetJoeBlack
  • 你的展示还不够。你在使用@RunWith(MockitoJunitRunner.class) 你在打电话给MockitoAnnotations.init(this) 或者别的什么吗?
  • 我正在正确地实例化 Mock
  • 您的问题是由您没有告诉我们的事情引起的。我复制了您的测试(如您的问题中所述)并且没有问题。根据错误消息,问题似乎是由您的类路径上不兼容的 jar 引起的。对于我的测试,我只使用了javax.ws.rs-api

标签: java spring unit-testing mockito


【解决方案1】:

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

例如,改变这个: when(context.getHeaderString("header1")).thenReturn("123456");

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

另外, 在命名模拟对象时考虑使用前缀mock。 在阅读 junits 时,它可能会非常有用 你写它们六个月后。

我在Mkyong 找到了不同的建议 确保您在依赖项中使用正确的javaee.jar。 同样,虽然不是完全匹配。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多