Reputation: 1445
I have a jUnit test which tests one of my functions. In that function I make a call to another class's method which I want to mock using mockito. However, I can't seem to actually mock this. Here is what my jUnit test looks like:
@Test
public void testingSomething() throws Exception {
mock(AuthHelper.class);
when(new AuthHelper().authenticateUser(null)).thenReturn(true);
Boolean response = new MainClassImTesting().test();
assertTrue(response);
}
EDIT: In my MainClassImTesting().test() function that I'm calling, it makes a call to authenticateUser() and passes it a hashMap.
Upvotes: 0
Views: 5975
Reputation: 129
Mockito will allow you create a mock object and have its methods return expected results. So in this case, if you want the authenticateUser method of your mocked AuthHelper instance return true regardless of the value of the HashMap parameter, your code would look something like this:
AuthHelper mockAuthHelper = mock(AuthHelper.class);
when(mockAuthHelper.authenticateUser(any(HashMap.class))).thenReturn(true);
However, your mocked object is useless to your MainClassImTesting unless it has access or reference to it. You can achieve that by adding AuthHelper to the constructor of MainClassImTesting so that the class (including your test method) has access to it.
MainClassImTesting unitUnderTest = new MainClassImTesting(mockAuthHelper);
Boolean response = unitUnderTest.test();
assertTrue(response);
Or if your test method is the only method that needs AuthHelper, you can simply make AuthHelper a method parameter.
MainClassImTesting unitUnderTest = new MainClassImTesting();
Boolean response = unitUnderTest.test(mockAuthHelper);
assertTrue(response);
Upvotes: 3
Reputation: 25960
If you want to mock the function call for any parameter of type A, just do :
AuthHelper authHelper = Mockito.mock(AuthHelper.class);
Mockito.when(authHelper.authenticateUser(any(A.class))).thenReturn(true);
Upvotes: 0