首页 > 解决方案 > 使用 Mockito 模拟接口,因此可以由 Jackson 序列化

问题描述

拥有一个简单的界面,例如

interface Foo {
  string getBar();
}

我想嘲笑它

    final Foo foo = Mockito.mock(
      Foo.class,
      withSettings()
        .serializable(SerializableMode.ACROSS_CLASSLOADERS)
        .withoutAnnotations()
        .stubOnly()
    );

然后可以用 Jackson 序列化它。

这样做时,杰克逊会抛出异常

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.mockito.internal.junit.DefaultStubbingLookupListener]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.mockito.internal.junit.DefaultStubbingLookupListener and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.exampleuser.model.domain.Foo$MockitoMock$479459786["mockitoInterceptor"]->org.mockito.internal.creation.bytebuddy.MockMethodInterceptor["mockHandler"]->org.mockito.internal.handler.InvocationNotifierHandler["mockSettings"]->org.mockito.internal.creation.settings.CreationSettings["stubbingLookupListeners"]->java.util.concurrent.CopyOnWriteArrayList[0])
    at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:293) ~[spring-web-5.1.10.RELEASE.jar:5.1.10.RELEASE]

如果您想知道,序列化发生在 REST Spring MVC 控制器中,我在间谍中返回该接口

    doReturn(Optional.ofNullable(foo)).when(userService).getOne(anyLong(), any());

所以它会在控制器中返回ResponseEntity.ok(foo)

标签: javaspringspring-mvcmockito

解决方案


推荐阅读