I’m learning JUnit, I know that assertEquals() invokes the equals() method to compare objects… so why the following test that compares two regex Pattern objects does not pass?
@Test
public void testTwoCompiledPattern()
{
assertEquals(Pattern.compile("test"), Pattern.compile("test"));
}
This one passes instead:
@Test
public void testTwoCompiledPattern()
{
assertEquals(Pattern.compile("test").toString(), Pattern.compile("test").toString());
}
Its because when you call the toString() method, both returns the “test” string because the Pattern class overrides it. But if you compare just the Pattern objects, they are 2 different objects, hence one is not equal to the other one, even though they have the same state.
The equals method checks for reference equality.