JUnit Assertion error expected and actual showing

2019-08-16 22:55发布

问题:

My expected and actual in my Assertionerror are showing the same thing. And they are the same reference. Anyone know why and how to fix? Code and error below. Thanks in advance:

@Test
public void test_CreateAUserWritesAFileReadsFilePrintsFile() throws IOException {
    //Arrange
    WriteCommand fwc = new FileWriteCommand();
    ReadCommand frc = new FileReadCommand();
    RegistrationController rc = new RegistrationController();
    User user = new User("Jerry", "123", "Engineer");
    rc.registerNewUser("Jerry", "123", "Engineer");
    fwc.writeUser(user);
    User one = frc.readUser("Jerry");
    System.out.println(one);
    User expected = one;

    //Act
    User actual = user;

    //Assert
    assertEquals(expected, actual);

}

Error

java.lang.AssertionError: expected: com.fdmgroup.userregistration.User<User [username=Jerry, password=123, role=Engineer]> but was: com.fdmgroup.userregistration.User<User [username=Jerry, password=123, role=Engineer]>

回答1:

That's because User user = new User("Jerry", "123", "Engineer"); is creating a new User object and User one = frc.readUser("Jerry"); is also creating a new User object. these two objects' field values are same but these two objects are different. However you can assert that by doing this.

assertThat(user).isEqualToComparingFieldByField(one);


回答2:

The fields have the same values, but the objects being compared are different.

Asserting equivalence between the fields of the objects should succeed, and unless I completely misunderstand what you are testing for, it's more correct.



标签: java junit