Reputation: 341
I started to study mocking. I want that test will fail when is called (only for study purpose).
MathUtils class:
public class MathUtils {
public int addWithHelper(int a, int b) {
MathUtilsHelper mathUtilsHelper = new MathUtilsHelper();
return mathUtilsHelper.addNumbers(a,b);
}
}
And my MathUtilsHelper:
public class MathUtilsHelper {
int addNumbers(int a, int b) {
return a + b;
}
}
Class MathUtilsTest
@Test
void itShouldAddNumberFromHelper() {
MathUtilsHelper mathUtilsHelperMocked = Mockito.mock(MathUtilsHelper.class);
when(mathUtilsHelperMocked.addNumbers(5,3)).thenReturn(999); // this doesn't works !!!!!!
int add = mathUtils.add(5, 3);
assertEquals(8, add); // should throw error
}
Thank you for any help!
Upvotes: 1
Views: 502
Reputation: 2992
MathUtils doesn't have the mocked object in it, you do as follows for MathUtils class:
public class MathUtils {
public MathUtilsHelper mathUtilsHelper;
public MathUtils(MathUtilsHelper mathUtilsHelper ){
this.mathUtilsHelper=mathUtilsHelper;
}
public int addWithHelper(int a, int b) {
return mathUtilsHelper.addNumbers(a,b);
}
}
And when initializing your test try this:
@Test
void itShouldAddNumberFromHelper() {
MathUtilsHelper mathUtilsHelperMocked = Mockito.mock(MathUtilsHelper.class);
when(mathUtilsHelperMocked.addNumbers(5,3)).thenReturn(999);
mathUtils= new MathUtils(mathUtilsHelperMocked);
int add = mathUtils.addWithHelper(5, 3);
assertEquals(8, add);
}
Upvotes: 1
Reputation: 5209
Your util class is creating a new instance of your helper each time, so will never use the mock.
I'm not sure why you need the util class to be honest, but if you want to make it easier to test, change it so that an instance of the helper is passed in on the constructor rather than instantiating it in the util class. Dependency injection in other words.
That way you can create the mock, and create an instance of the util class by passing in the mock.
Upvotes: 1