Not understanding, why test fails at specific line in daily test

Hi there,
I have already writte many tests yesterday and today I looked at the daily test results, especially at the Prog2.tests.daily.TestsCorrect::all daily test, because atleast that should not fail.
From the output

uri.tests.UserInfoTests.testUserInfoWithColon(UserInfoTests.java:41): AssertionError: null

I gathered, that there is something wrong with the testUserInfoWithColon test.
The output shows, that the “Assertion: null” error occurs in this line:
assertTrue(UserInfo == "user:password");

The problem is, that I don’t know how that happened, since I have checked if UserInfo is null with a previous assertion:

@Test
public void testUserInfoWithColon() {
    Uri uri = /* created working uri object with UriParserFactory.create(...).parse(); */
    assertNotNull(uri);
    String UserInfo = uri.getUserInfo();
    assertNotNull(UserInfo);
    assertTrue(UserInfo == "user:password");
}

Is there something wrong with the comparison at the end?
This happens with most other tests that use assertTrue() with a string comparison, so I think it must be a problem with the comparison.

Thanks in advance!

Hi, in Java you should compare Strings using the equals method. To compare e.g. the Strings s1 and s2
you would write

s1.equals(s2)

Hope this solves your problem.

The only caveat to using equals (i.e. the member function of the class String) is that it will throw a NullPointerException if one or both are null. However in this project null is a valid return value for getUserInfo and getQuery. So it is better to use equals from the class Objects instead:

Objects.equals(s1, s2);

This method handles the case when null is involved and uses the first object’s equals method when possible.

See here for the documentation.

2 posts were split to a new topic: JUnit assert message as first or second argument

No. a.equals(b) throws a NullPointerException if a is null. If b is null, it should return `false.

Thus the correct way to test that a is some constant is to do it like this: "foo".equals(a), and not a.equals("foo").