Sobes.tech
Senior

What happens if you forget to mock a method in a Mockito test and it gets called during the test?

sobes.tech AI

Answer from AI

If in a Mockito test you forget to mock a method, and that method is called during the test execution, the behavior depends on the type of mock:

  • For regular mocks (created with mock()), calling an unmocked method will return the default value: null for objects, 0 for numbers, false for booleans.
  • For spies (created with spy()), calling a method by default will execute the real implementation if the method was not mocked.

This can lead to unexpected results in the test: for example, if the method returns null and the code does not expect this, a NullPointerException may occur. Or if the method calls external dependencies, the test may become unstable.

Therefore, it is important to explicitly define the behavior of mocks for all called methods to ensure the test is predictable and isolated.