javajunitassertions

Junit: Assert.assertNotSame returning true despite the fact the two strings are equal


I'm using JUnit 4.12 and PowerMock 1.6.2. I have the following code:

import org.junit.Assert;
...
System.out.println("equals?" + obj.equals(myObj.getUser().getUserName()));
Assert.assertNotSame(obj.getUserName(), myObj.getUser().getUserName());

The system out call prints equals? true, however the following assert line succeeds, where I expect it to fail if the strings are equal. Why isn't assertNotSame not working and what is the proper method I should be using?


Solution

  • assertNotSame(a, b) checks that a != b, i.e. that a and b are not references to the exact same object. That's very different from testing that a.equals(b) is false, which checks that the two string don't have the same characters.

    You should use

    assertFalse(obj.getUserName().equals(myObj.getUser().getUserName()))
    

    I would recommend using AssertJ, which has dozens of much more expressive assertions:

    assertThat(myObj.getUser().getUserName()).isNotEqualTo(obj.getUserName());