简体   繁体   中英

Java test fails (tostring)

I have this Java program, but my test gives me this message:

testEmployeeTostring: failed testEmployeeTostring expected <[id[= 1013, name= Jubal Early, job = ]procurement]> but was: <[id[= 1013, name= Jubal Early, job = ] procurement]>

I had to use @Override and I think that's the problem. I hope someone can figure out the problem with this:

public class Employee {

        int id;
        String name;
        JobType job;

        public Employee(int id, String name, JobType job)
        {
                this.id = id;
                this.name = name;
                this.job = job;
        }

        @Override public String toString()
        {
                return ("["+ "id =" + id + ", name = "  + name + ", job = " + job + "]");
        }
}

There is a space between ] and 'procurement'

job = ] procurement

使用断言语句在预期的String中有一个额外的空格。

Are you sure you have equals() method overriden? JUnit uses equals() to compare objects. Overriding hashCode() is always a good idea as well:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Employee)) return false;
    Employee employee = (Employee) o;
    return id == employee.id && job == employee.job && name.equals(employee.name);

}

@Override
public int hashCode() {
    int result = id;
    result = 31 * result + name.hashCode();
    result = 31 * result + job.hashCode();
    return result;
}

The code above assumes all fields are non-nullable and that JobType is an enum . And BTW toString() might have nothing to do here, as long as you are comparing objects, not toString() of objects (bad practice).

这可能是由于JobType.toString()方法返回一个额外的空间而发生的。

我相信你在返回toString()方法的字符串中有一些额外的空格,从而使得返回的字符串(稍微)与测试期望的字符串不同。

With String a and String b ,

are you doing an a == b instead of a.equals(b) ?

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