简体   繁体   中英

JUnit and checking fields for null

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)

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());
}

When you want to assert null value, you should use

assertNull()

Also, you assign "new Man()" to "m" variable, but in asserts you use "e" variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM