JUnit and checking fields for null

Gabesz07 :

When I test the default cons. in a class like this:

public class Man {
    public Man(){}

@Test
public void defConstructorTest() {
    Man m = new Man();
    assertEquals(0, m.getName());
    assertEquals(0, m.getBorn());

comes the message:

test failed expected: 0 but was: null

When I change the code like this:

@Test
public void defConstructorTest() {
    Man m = new Man();
    assertEquals(null, m.getName());
    assertEquals(null, m.getBorn());

test failed again with this message is shown:

expected: null but was: 0

Can somebody explain why am I getting this error? (Getters are working fine)

Mureinik :

You haven't shared enough code of Man to give a definite answer, but from the error messages (and some common sense) I'd guess that getName() returns a String and getBorn() returns an int with the year the man was born on. Assuming these are just simple getters that return data members, the default for a String (or any other object, for that matter) is null unless it's explicitly initialized, and the default for a primitive int is 0.

To make a long story short, you need to expect the right default value for each getter:

@Test
public void defConstructorTest() {
    Man m = new Man();
    assertNull(m.getName());
    assertEquals(0, m.getBorn());
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=128587&siteId=1
Recommended