最近,我开始使用Kotlin,在使用Spring测试JSON映射时遇到了一些奇怪的行为
@SpringBootTest(classes = [TestApplication::class]) class JacksonIntegrationTest { @Autowired lateinit var objectMapper: ObjectMapper var objectMapperTest = TestObjectMapper() @Test fun `should serialize and deserialize object`() { //given val value = SealedObject //when val jsonTest = objectMapperTest.writeValueAsString(value) val resultTest: SealedObject = objectMapperTest.readValue(jsonTest) val json = objectMapper.writeValueAsString(value) val result: SealedObject = objectMapper.readValue(json) //then` assertThat(result).isSameAs(value) assertThat(resultTest).isSameAs(value) <---------- FAILED } internal sealed class Sealed internal object SealedObject: Sealed() }
value=插孔集成测试$SealedObject@6727e0cd<-------------结果(弹簧)=千斤顶集成测试$SealedObject@6727e0cd<;-----相同内存位置结果测试(OWN)=插孔集成测试$SealedObject@3c8e3f98
正如您所看到的,spring-objectmapper返回的值在内存中具有与基值相同的引用。但自己创建的objectmapper返回的对象在内存中的不同位置。为什么?
所有结果应具有相同的存储位置