如何在特定对象特定字段的实例传递时存根方法?

时间:2014-10-16 10:08:26

标签: java unit-testing matcher hamcrest

我希望在[name =“Mohammad”,age = 26]调用Person类的实例时返回4。 我希望在[name =“Ali”,age = 20]调用Person类的实例时返回5。

所以我有这些课程:

public class Person {
    private String name;
    private int age;

我的DAO课程:

public class DAO {
    public int getA(Person person) {
        return 1;
    }

    public int getB(Person person) {
        return 2;
    }
}

这是计算器类

   public class Calculator {
        private DAO dao;

        public int add() {
            dao = new DAO();
            return dao.getA(new Person("Mohammad", 26)) +
                    dao.getB(new Person("Ali", 20));
        }
    }

这是我的测试:

    @Test
    public void testAdd() throws Exception {

        when(mydao.getA(new Person("Mohammad", 26))).thenReturn(4);
        when(mydao.getB(new Person("Ali", 20))).thenReturn(5);
        whenNew(DAO.class).withNoArguments().thenReturn(mydao);

        assertEquals(9, cal.add());
    }

那么为什么我的考试会失败呢?

2 个答案:

答案 0 :(得分:2)

new Person("Mohammad", 26)类中的

Calculator和测试类中的new Person("Mohammad", 26)不相等,因为您没有覆盖equals类中的Person方法。

覆盖Person类中的equals方法,如下所示

 @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (age != person.age) return false;
        if (name != null ? !name.equals(person.name) : person.name != null) return false;

        return true;
    }

覆盖hashCode方法

时,覆盖equals()是必要的

答案 1 :(得分:1)

我不太确定您正在使用哪个测试框架,但是在when()调用中使用的Person实例与您在Calculator类中使用的实例不同,因此除非您重写equals()和hashcode ()在人物中,他们不会被视为匹配。

您的IDE应该能够生成合适的默认equals()和hashcode()方法。

相关问题