Does mocking a method using mockito ensures that mocked method will never be called? I have Main class which contains some code i want to write unit tests for and i have one unit test class MainTest which contains unit tests for Main class.
eg:
Source Class:
package abc;
public class Main {
public int check1() {
int num = 10;
num = modify(num);
return num;
}
public int modify(int num) {
if (num % 10 == 0) return num / 10;
return -1;
}
}
Junit Test (using mockito)
package abc;
import junit.framework.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
public class MainTest {
private static Main main;
@BeforeClass
public static void setUp() {
main = Mockito.mock(Main.class);
Mockito.when(main.modify(10)).thenReturn(5);
}
@Test
public void testCheck1() {
Test1 main1 = new Main();
int num = main.check1();
Assert.assertEquals(5, num);
}
}
This test is failing. Why?
EDITED
Because you didn’t provide a behavior for
check1(). ALL methods get mocked, so without you providing a behavior,check1()returns a default value for the return type of int, which is 0. Furthermore,check1()since it is mocked does not even get to callmodify().If you are trying to test a class, you never mock the Class Under Test. On rare occasion, you might have to Spy a class under test. Rather, you mock collaborators only.
I am guessing your example was a contrived one (I hope). But if you are writing and testing a class where you think you want to modify some internal method’s behavior, I see two likely probabilities:
check1()hard-codes the value it passes tomodify(), which is why you are trying to mockmodify(). If instead that value were a parameter tocheck1()or a settable field in classMain, then there wouldn’t even be a need to use a mock at all.