I am trying to assert that 2 arrays of a UserDto
object are equal to one another in a unit test that I am implementing. See below my UserDto
class and the 2 UserDto
instances I am trying to compare
UserDto
class:
public record UserDto(
@NotBlank Long id,
@NotBlank String name,
@NotBlank String lastname,
@NotBlank String email,
@NotBlank String[] roles) {
}
Instances of UserDto
UserDto basicUserDto = new UserDto(
2L,
"donquixote",
"doflamingo",
"doffy@acme.com",
new String[]{"ROLE_USER"}
);
UserDto accountantUserDto = new UserDto(
3L,
"monkey",
"d-luffy",
"luffy@acme.com",
new String[]{"ROLE_ACCOUNTANT"}
);
Below I have my expected and actual objects, and my assertArrayEquals()
call:
UserDto[] expectedDtoArray = new UserDto[]{basicUserDto, accountantUserDto};
UserDto[] actualDtoArray = userHelper.buildUserDtoArray(List.of(basicUser, accountantUser));
assertArrayEquals(expectedDtoArray, actualDtoArray);
when I run this test, I get the following response:
array contents differ at index [0], expected: <UserDto[id=2, name=donquixote, lastname=doflamingo, email=doffy@acme.com, roles=[Ljava.lang.String;@79d06bbd]> but was: <UserDto[id=2, name=donquixote, lastname=doflamingo, email=doffy@acme.com, roles=[Ljava.lang.String;@2caa5d7c]>
Expected :UserDto[id=2, name=donquixote, lastname=doflamingo, email=doffy@acme.com, roles=[Ljava.lang.String;@79d06bbd]
Actual :UserDto[id=2, name=donquixote, lastname=doflamingo, email=doffy@acme.com, roles=[Ljava.lang.String;@2caa5d7c]
Is there a way to assert that 2 array of objects with an array field are equal without having to manually implement separate method that will compare the 2 array fields?
I tried converting both arrays to a String
object using the toString()
method, which did not work. I also tried using ObjectMapper.writeValueAsString()
method which also did not work.
I did not implement the equals
method in my UserDto
class.
See below equals
method implementation. Since the id field is a unique field, if the UserDto
objects have the same id
field, both objects will be considered equal.
equals()
implementation below:
@Override
public boolean equals(Object o) {
UserDto dto = (UserDto)o;
if (this.id.equals(dto.id)){
return true;
}
return false;
}