Search code examples
javaunit-testingmatcherhamcrest

How to stub a method when instance of specific object specific fields passed?


I want to return 4 when instance of Person class by [name = "Mohammad", age = 26] where called. I want to return 5 when instance of Person class by [name = "Ali", age = 20] where called.

So I have these classes:

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

My DAO class:

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

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

Here is calculator class

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

and this is my test:

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

So why my test will failed?


Solution

  • new Person("Mohammad", 26) in Calculator class and new Person("Mohammad", 26) in your test class is not equal since you have not overwrite equals method in Person class.

    Overwrite equals method in Person class as below

     @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;
        }
    

    Overwriting hashCode is nesssacery when overwriting equals() methods