I am new to using Mockito while I am verifying certain method should be called with a specific parameter, while all the value type parameter (int, String, enum etc) could be verified, but reference/class type parameter seems not, here is an example
// my actual class
public class MyActualClass {
public void processRequest() {
User curUser = MyUtils.getUserFromOtherPlace(UserType.ADMIN);
processAnotherRequest(1, "address", curUser);
}
public void processAnotherRequest(int userId, String address, User user) { ... }
}
public static class MyUtils{
public static getUserFromOtherPlace(UserType userType) {
User newUser = new User();
if (userType == UserType.ADMIN) {
newUser.setAccess(1);
}
//...
return newUser
}
}
// my test class
public class MyActualClassTest{
@Mock
private MyActualClass myActualClass;
@Test
public void testIfMethodBeingCalledCorrectly() {
User adminUser = new User();
adminUser.setAccess(1);
doCallRealMethod().when(myActualClass).processRequest();
myActualClass.processRequest();
verify(myActualClass).processAnotherRequest(1, "address", adminUser);
}
}
I know it might because the adminUser
set in my test method was not the same reference object that'd be generated through my actual method getUserFromOtherPlace -> MyUtils.getUserFromOtherPlace, I also tried to mock the return object with my static method like
// tried 1
when(MyUtils.getUserFromOtherPlace(UserType.ADMIN).thenReturn(adminUser); // this throws error like "You cannot use argument matchers outside of verification or stubbing", and suggest using eq()
// tried 2
when(MyUtils.getUserFromOtherPlace(eq(UserType.ADMIN)).thenReturn(adminUser); //this throws NullPointer exception in getUserFromOtherPlace when check the input enum parameter "userType"
So how could I pass the reference object into my entry method and mock it as return value of my internal method here? BTW, if my method only contains value type parameter, it will work...
So in order to mock you static method you will need to:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ MyUtils.class })
//your test class here
@Before
public void setup() {
PowerMockito.mockStatic(MyUtils.class);
when(MyUtils.getUserFromOtherPlace(UserType.ADMIN).thenReturn(adminUser);
}
But I always prefer not to mock static classes if there is another option so maybe you could try a argument captor:
//test class
@Captor
private ArgumentCaptor<User> captor;
//your test
@Test
public void testIfMethodBeingCalledCorrectly() {
doCallRealMethod().when(myActualClass).processRequest();
myActualClass.processRequest();
verify(myActualClass, times(1)).processAnotherRequest(1, "address",
captor.capture());
Assert.assertEquals(1, captor.getValue().getAccess());
}