我有以下问题。
这是我的Accident
班和CommonDomainEntity
班:
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Accident extends CommonDomainObject {
private String status;
private Date accidentDate;
private String name;
}
@Data
public abstract class CommonDomainObject {
public Long id;
public boolean isNew() {
return null == getId();
}
}
在我的测试课中,我打电话给以下人:
String exp = objMapper.writeValueAsString(accidents);
System.out.println(exp);
ResponseEntity<String> res = restTemplate.getForEntity("/accidents", String.class);
assertEquals(HttpStatus.OK, res.getStatusCode());
JSONAssert.assertEquals(exp, res.getBody(), false);
它引发以下错误:
java.lang.AssertionError: [id=2]
Expected: new
but none found
; [id=3]
Expected: new
but none found
我已经尝试打印出对象exp
以查看其中的内容,以及尝试打印出s in
事故的内容。
正如您在控制台日志中看到的那样,出于某种原因,exp
对象中有一个new=false
字段,我无法弄清楚它的来源。
这就是我的事故清单
Accident(status=pending, accidentDate=null, name=Name),
Accident(status=closed, accidentDate=null, name=Name)]
这是我的exp
对象,为JSON
[{"id":2,"status":"pending","accidentDate":null,"name":"Name","new":false},
{"id":3,"status":"closed","accidentDate":null,"name":"Name","new":false}]
答案 0 :(得分:1)
在我看来,您正在将事故列表转换为字符串,并将其与来自也是字符串的restTemplate调用的响应进行比较。其余服务将返回不属于Accident对象的其他属性。解决方法是向事故对象添加额外的属性,以使服务响应与域模型保持一致
答案 1 :(得分:0)
CommonDomainObject.isNew()
将抽象类中的ObjectMapper
方法评估为JSON字段。您必须使用杰克逊注释将其排除。
public abstract class CommonDomainObject {
...
@JsonIgnore
public boolean isNew() {
return null == getId();
}
}
请参阅:
您的MCVE为:
objMapper.writeValueAsString()
new
字段所有其他代码都可用于复制您的问题:)