Reputation: 23
I have the following problem.
Here is my Accident
class and the CommonDomainEntity
class:
@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();
}
}
In my test class I am calling the following:
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);
It throws the following error:
java.lang.AssertionError: [id=2]
Expected: new
but none found
; [id=3]
Expected: new
but none found
I already tried to out print the object exp
to see whats in it, as well as I tried to print whats in
accidents`.
As you see in the console logs, for some reason in the exp
object there is a new=false
field, and I can`t figure out where this is from.
This right here is what is in my accidents List
Accident(status=pending, accidentDate=null, name=Name),
Accident(status=closed, accidentDate=null, name=Name)]
And this is my exp
object as JSON
[{"id":2,"status":"pending","accidentDate":null,"name":"Name","new":false},
{"id":3,"status":"closed","accidentDate":null,"name":"Name","new":false}]
Upvotes: 2
Views: 2358
Reputation: 19876
Your CommonDomainObject.isNew()
method in the abstract class is evaluated as a JSON field by ObjectMapper
. You must exclude it using jackson anotations.
public abstract class CommonDomainObject {
...
@JsonIgnore
public boolean isNew() {
return null == getId();
}
}
See:
Your MCVE would be:
objMapper.writeValueAsString()
new
fieldAll the other code is reduntant for the reproduction of your issue :)
Upvotes: 4