Is it possible to verify that some fields, for example, of the DTO object is not “affected” during unit testing?
Example:
Imagine we have some DTO to sent via rest:
public class CallbackDTO {
private Long id;
private String status;
private Long checkPointId;
private List<CallbackDetails> details;
private OffsetDateTime sysdate;
// getters and setters
}
class CallbackDetails {
private String propertyName;
private String propertyValue;
private Map<String, String> additionalProperties;
// getters and setters
}
And i have some code that sends a two diffrent “callbacks”:
public class CallbackSender {
public CallbackDTO sendCallbackToOneSystem() {
var callback = new CallbackDTO();
callback.setId(1L);
callback.setStatus("NEW");
return callback;
}
public CallbackDTO sendCallbackToAnotherSystem() {
var callback = new CallbackDTO();
callback.setId(2L);
callback.setStatus("FINISHED");
callback.setSysdate(OffsetDateTime.now());
callback.setCheckPointId(1L);
callback.setDetails(
List.of(
new CallbackDetails()
.setPropertyName("some-property")
.setPropertyValue("some-value")
.setAdditionalProperties(
Map.of(
"request-id", UUID.randomUUID().toString(),
"correlation-header-name", "x-correlation-id",
"correlation-header-ref", "request-id"
)
)
)
);
return callback;
}
}
So, i write a unit test for method:
@Test
void sendCallbackToOneSystem() {
var cs = new CallbackSender();
var callback = cs.sendCallbackToOneSystem();
assertEquals(1L, callback.id());
assertEquals("NEW", callback.status());
// and here I want to make sure that NO OTHER FIELDS have been "touched"/set
}
Well, my question is how to do an assertions, that method sendCallbackToOneSystem
does nothig with any fields of CallbackDTO
except id
and status
?
Ofcource i can assert for all possible fields for “default” values (eg null or 0 or empty etc) but may be there is a more elegant way ?
In example that you provided method has no parameters and DTO is created inside. There is no way how you can verify on what exactly happens to this object.
public DTO do() {
DTO dto = new DTO();
//Do anything
}
If you had something like this instead:
public DTO do(DTO dto) {
//Do anything
return dto;
}
You could use assertj https://assertj.github.io/doc/#assertj-core-recursive-comparison-ignoring-fields
DTO input = new DTO();
DTO output = object.do(input);
assertThat(input).usingRecursiveComparison()
.ignoringFields("id")
.isEqualTo(output);
1