Hypothesis: your Student
class does not implement .equals()
/.hashCode()
.
By default, when()
you mock a method call, mockito will check whether its argument(s) .equals()
the one(s) you have passed it as (an) argument(s) to the mocked method.
However, if you don't implement .equals()
, then you will have the case that:
final Student s1 = new Student("foo", "bar");
final Student s2 = new Student("foo", "bar");
s1.equals(s2); // <--- FALSE!
And this is what happens here. In your first scenario, you create a Student
which appears, to you, logically equal but that is not what Mockito wants. Therefore, in your first scenario, .get()
will return null
.
In your second however, you pass the same reference; since you don't implement .equals()
, Object
's .equals()
takes place, and for this .equals()
implementation, obj1.equals(obj2)
if and only if obj1 == obj2
-- which is the case. Continuing the code above, in your case:
s1 == s2; // FALSE! (as in first test)
s1 == s1; // true (as in second test)
If you wanted to be more "loose" to arguments, you'd have to write custom argument matchers; Mockito can also do that (with the help of its hamcrest dependency).
All this banter to say that you should solve your problem by making your Student
class implement .equals()
/.hashCode()
.