Sebastian D'Agostino
Sebastian D'Agostino

Reputation: 1675

JUnit test case failure: java.lang.AssertionError: expected null, but was:<null>

I am using JUnit 4.12 and Jackson

@Test
public void testFailToGetDataAsString() {
    Receipt receipt = new Receipt(null);

    assertNull(receipt.getDataAsString());
}

The method I am testing is the following (this.data is just a null Map):

public String getDataAsString() {
    try {
        return new ObjectMapper().writeValueAsString(this.data);
    } catch (Exception e) {
        return null;
    }
}

Finally I run the test and check that "null" is not "< null >".

Upvotes: 2

Views: 8736

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36473

getDataAsString() does not return null because return new ObjectMapper().writeValueAsString(this.data); does not throw an exception, instead it returns a string that says "< null >" and that does not equal to null of course. Instead of only returning null on catching an exception you should return null too if writeValueAsString() returns this custom null type.

Upvotes: 5

Sebastian D&#39;Agostino
Sebastian D&#39;Agostino

Reputation: 1675

I finally changed the method code to:

public String getDataAsString() {
    try {
        if (this.data != null) {
            return new ObjectMapper().writeValueAsString(this.data);
        }
    } catch (Exception e) {
    }
    return null;
}

I really don't know why this works and the previous one not.

Upvotes: 1

Related Questions