In unit testing with JUnit, why do we use mocking frameworks like Mockito?
Think about how dependencies affect the behavior of the unit you want to test.
Mocking replaces real dependencies with fake ones that behave in a controlled way. This helps test only the unit's logic without interference from other parts.
What is the output of this JUnit test when the mocked dependency returns 5?
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class Calculator { Dependency dep; Calculator(Dependency dep) { this.dep = dep; } int compute() { return dep.getValue() * 2; } } interface Dependency { int getValue(); } public class CalculatorTest { @Test void testCompute() { Dependency mockDep = mock(Dependency.class); when(mockDep.getValue()).thenReturn(5); Calculator calc = new Calculator(mockDep); assertEquals(10, calc.compute()); } }
Check what value the mock returns and how compute() uses it.
The mock returns 5 for getValue(), so compute() returns 5 * 2 = 10, matching the assertion.
Which assertion correctly verifies that the mocked dependency's method was called exactly once?
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; interface Service { void perform(); } public class ServiceTest { @Test void testPerformCalled() { Service mockService = mock(Service.class); mockService.perform(); // Which assertion below is correct? } }
Mockito uses verify() to check method calls, not assertEquals.
Option B uses Mockito's verify() with times(1) to check perform() was called once. Other options misuse assertions or method calls.
Given this test code, why does it throw NullPointerException?
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class Processor { Helper helper; Processor(Helper helper) { this.helper = helper; } int process() { return helper.getData() + 1; } } interface Helper { Integer getData(); } public class ProcessorTest { @Test void testProcess() { Helper mockHelper = mock(Helper.class); Processor proc = new Processor(mockHelper); assertEquals(2, proc.process()); } }
What does a mock return if no behavior is defined?
Mocks return default values like null for objects. Adding 1 to null causes NullPointerException.
In a complex system with multiple dependencies, how does mocking help isolate the unit under test in JUnit?
Think about controlling dependencies to avoid unpredictable behavior.
Mocking replaces dependencies with controlled fakes, so the unit test runs fast and reliably without external side effects.