java - 使用 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)
解决方案
推荐阅读
- android - 在我的项目中添加 AdMob 广告时出现错误
- c# - LINQ - 将字符串转换为日期时间顺序
- python - keras - 使用 lambda 层时如何避免尺寸错误
- javascript - Javascript 日期 | 将日期设置为一年的最后一秒
- powershell - 获取 3rd 方模块的 cmdlet 参数信息
- vuejs2 - 使用带参数的自定义规则(vue js - vee validate)
- angular - 当我第二次切换到显示状态时,动画状态没有切换
- c# - 避免嵌套 if/else if 以及在条件语句中同时避免 InvalidOperationException
- html - CSS Masonry Layout:瓷砖动态高度的问题
- php - 将值从视图传递和隐藏到控制器 - Codeigniter