Home > Back-end >  Error when using mockito.mock(<SomeObject>.class) and object mapper
Error when using mockito.mock(<SomeObject>.class) and object mapper

Time:11-14

Im getting an InvalidDefinitionException when I try to map a mocked object with ObjectMapper. The object doesn't matter in that case. The code which produces the exception looks like this:

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValueAsString(mock(Object.class));

The resulting exception message is this:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.mockito.internal.creation.bytebuddy.ByteBuddyCrossClassLoaderSerializationSupport and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.mockito.codegen.Object$MockitoMock$nY0RyieU["mockitoInterceptor"]->org.mockito.internal.creation.bytebuddy.MockMethodInterceptor["serializationSupport"])

The ObjectMapper comes from jackson-databind v2.14.0, for mockito I'm using version 4.8.1

CodePudding user response:

TL; DR

Mock objects aren't data structures, you can't serialize them by ObjectMapper.

Full answer

You are trying to serialize a mock object which is very special kind of object created by Mockito. It is very different from a ordinary data structures that are processable by ObjectMapper.

What ObjectMapper does is that it looks at the members of a serialized object and tries to serialize each of them. It either knows, how to do that (int, Long...), or it is configured, how the should be serialized or the serialized member has some annotations to tell the ObjectMapper. In your case the mock object has a member of type ByteBuddyCrossClassLoaderSerializationSupport and ObjectMapper has no idea what to do.

  • Related