Sunday, November 15, 2015

Stubbing a method with Class field

Consider the scenario where you have to stub a method using when. In a case where parameter is a class not an object then the Matchers.any will not help in that case. Following is the code to be tested and one wrong way of stubbing.
// code to be tested
Long primaryKey = 12345L;
final App app = getEntityManager().find(App.class, primaryKey);

// stubbing the find method
when(em.find(Matchers.any(Class.class), Matchers.same(primaryKey)))
.thenReturn(app);
Instead of using Matchers.any we should use Matchers.isA as the way of stubbing. Following is correct way of stubbing in this setup.
when(em.find((Class) Matchers.isA(Class.class), Matchers.same(primaryKey)))
.thenReturn(app);
The original answer was found on stackoverflow.

No comments: