nix*_*get 5 java json unit-testing jackson objectmapper
我在 Spring Boot 项目中使用 Jackson 进行序列化/反序列化。
我有一个具有以下结构的 DTO 对象,
public class TestDTO implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private UUID certificateId;
@NotNull
private Long orgId;
@NotNull
private CertificateType certificateType;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Valid
@NotNull
private PublicCertificateDTO publicCertificate;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Valid
private PrivateCertificateDTO privateCertificate;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private ZonedDateTime expiryDate;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private ZonedDateTime createdDate;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private ZonedDateTime updatedDate;
}
Run Code Online (Sandbox Code Playgroud)
使用以下方法在我的单元测试中序列化此对象,
public static byte[] convertObjectToJsonBytes(TestDTO object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);
return mapper.writeValueAsBytes(object);
}
Run Code Online (Sandbox Code Playgroud)
导致具有WRITE_ONLY访问权限的字段被忽略(出于显而易见的原因)。所以在序列化对象我看到空值publicCertificate和privateCertificate。
我确实尝试设置 mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
有没有其他方法可以忽略单元测试的这些属性?
虽然指定的解决方案有效,但对于需求来说是一种矫枉过正。如果您只想覆盖注释,则不需要自定义序列化程序。Jackson 有一个mixin 功能可以满足这些微不足道的要求
考虑以下简化的 POJO:
public class TestDTO
{
public String regularAccessProperty;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
public String writeAccessProperty;
}
Run Code Online (Sandbox Code Playgroud)
如果要覆盖@JsonProperty注释,请创建另一个具有完全相同名称(或相同 getter/setter 名称)的变量的 POJO :
// mixin class that overrides json access annotation
public class UnitTestDTO
{
@JsonProperty(access = JsonProperty.Access.READ_WRITE)
public String writeAccessProperty;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过 Simplemodule 将原始 POJO 和 mixin 关联起来:
simpleModule.setMixInAnnotation(TestDTO.class, UnitTestDTO.class);
Run Code Online (Sandbox Code Playgroud)