What is the point in unit testing mock returned data?

user4235401 :

Consider the scenario where I am mocking certain service and its method.

Employee emp = mock(Employee.class);
when(emp.getName(1)).thenReturn("Jim");
when(emp.getName(2)).thenReturn("Mark");

//assert
assertEquals("Jim", emp.getName(1));
assertEquals("Mark", emp.getName(2));

In the above code when emp.getName(1) is called then mock will return Jim and when emp.getName(2) is called mock will return Mark. My Question is I am declaring the behavior of Mock and checking it assertEquals what is the point in having above(or same kind of) assert statements? These are obviously going to pass. it is simply like checking 3==(1+2) what is the point? When will these tests fail (apart from changing the return type and param type)?

Mureinik :

As you noted, these kind of tests are pointless (unless you're writing a unit test for Mockito itself, of course :-)).

The point of mocking is to eliminate external dependencies so you can unit-test your code without depending on other classes' code. For example, let's assume you have a class that uses the Employee class you described:

public class EmployeeExaminer {
    public boolean isJim(Employee e, int i) {
        return "Jim".equals(e.getName(i));
    }
}

And you'd like to write a unit test for it. Of course, you could use the actual Employee class, but then your test won't be a unit-test any more - it would depend on Employee's implementation. Here's where mocking comes in handy - it allows you to replace Employee with a predictable behavior so you could write a stable unit test:

// The object under test
EmployeeExaminer ee = new EmployeeExaminer();

// A mock Employee used for tests:
Employee emp = mock(Employee.class);
when(emp.getName(1)).thenReturn("Jim");
when(emp.getName(2)).thenReturn("Mark");

// Assert EmployeeExaminer's behavior:
assertTrue(ee.isJim(emp, 1));
assertFalse(ee.isJim(emp, 2));

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=467688&siteId=1