【问题标题】:How to stub a method when instance of specific object specific fields passed?当特定对象特定字段的实例通过时如何存根方法?
【发布时间】:2014-10-16 10:08:26
【问题描述】:

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

那么为什么我的测试会失败?

【问题讨论】:

    标签: java unit-testing matcher hamcrest


    【解决方案1】:

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

    如下覆盖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;
        }
    

    在覆盖 equals() 方法时,覆盖 hashCode 很重要

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 2012-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多