🎯 What you will learn

Mockito is the most widely used mocking framework for Java. It lets you replace real dependencies — databases, HTTP clients, email gateways — with controlled fakes so you can test a single class in isolation. By the end of this lesson you will understand:

  • @Mock to create fake implementations of interfaces and classes
  • @ExtendWith(MockitoExtension.class) to activate Mockito in JUnit 5
  • when(mock.method()).thenReturn(value) to stub return values
  • verify(mock, times(n)).method(args) to assert interactions
  • never(), any(), eq(), contains(), argThat() matchers
  • doThrow() for void methods and error-path testing
  • The difference between @Mock and @Spy
💼 Interview reality: "How do you mock a dependency in JUnit 5?" and "What is the difference between @Mock and @Spy?" are asked in almost every Java backend interview. Knowing the AAA pattern with Mockito is essential.

💼 Real-world scenario

💼
TaxSetu (Bangalore, India)
Test the filing service without a real database

TaxFilingService depends on ITRRepository (database) and NotificationService (email gateway). Rohan replaces both with Mockito mocks — no real DB, no real emails. He stubs hasFiled() to return false/true, then verifies that save() and send() are called with the right arguments.

🎭 @Mock, @ExtendWith, when/thenReturn

The AAA pattern — Arrange (stub the mock), Act (call the real service), Assert (check the result). @ExtendWith(MockitoExtension.class) initialises all @Mock fields before each test.

mvn test -Dtest=TaxFilingServiceTest#successfulFiling_returnsSubmittedResult
TaxFilingServiceTest.javaLesson 32 · @Mock, @ExtendWith, when/thenReturn
verified output
[INFO] Running io.taxsetu.TaxFilingServiceTest [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.370 s [INFO] BUILD SUCCESS

AAA pattern: Arrange — set up the mock's stubbed behaviour. Act — call the method under test. Assert — check return values and, if needed, verify interactions. Keep the three sections visually separated in every test for readability.

✅ verify() interactions

verify(mock) asserts that a method was called. verify(mock, times(n)) checks exact call count. verify(mock, never()) asserts the method was never called — critical for error path tests.

mvn test -Dtest=TaxFilingServiceTest
TaxFilingServiceTest.javaLesson 32 · verify() interactions
verified output — all 3 service tests pass
[INFO] Running io.taxsetu.TaxFilingServiceTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.370 s -- in io.taxsetu.TaxFilingServiceTest [INFO] BUILD SUCCESS

🔬 Argument matchers + doThrow

Argument matchers let you match method calls flexibly. You must use matchers for all arguments or none — never mix raw values and matchers in the same call (use eq() to wrap a literal).

mvn test
TaxFilingServiceTest.javaLesson 32 · argument matchers + full suite
verified output — complete suite: 12 tests
[INFO] Tests run: 9, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.044 s -- in io.taxsetu.TaxCalculatorTest [INFO] Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.370 s -- in io.taxsetu.TaxFilingServiceTest [INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0 [INFO] BUILD SUCCESS [INFO] Total time: 0.938 s

@Spy vs @Mock: @Mock fakes all methods — every method returns a default (null, 0, false) unless stubbed. @Spy wraps a real object and only intercepts methods you explicitly stub; the rest call the real implementation. Use @Mock for full control; @Spy when you want mostly real behaviour with one or two stubbed methods.

📋 Mockito quick reference

OperationSyntaxPurpose
Stub return valuewhen(mock.method(args)).thenReturn(value)Arrange step — define fake response
Stub exceptionwhen(mock.method(args)).thenThrow(new Ex())Test error paths for non-void methods
Stub void methoddoThrow(new Ex()).when(mock).method(args)Void methods can't use when() directly
Verify call countverify(mock, times(n)).method(args)Assert method called n times
Verify never calledverify(mock, never()).method(any())Assert method was not invoked
Any argumentany(), anyString(), anyInt()Match any value of that type
Exact valueeq("literal")Match exact value when mixing matchers
Custom predicateargThat(obj -> condition)Match by arbitrary logic

🎤 Interview Q&A

EasyWhat is the AAA pattern in unit testing?
+

Arrange: set up the object under test and stubs. Act: call the method being tested. Assert: verify the return value, state change, or interactions. The three sections should be visually separated in every test for readability.

EasyWhat happens if you don't stub a mock method and the code calls it?
+

Mockito returns "nice" defaults: null for objects, 0 for numbers, false for booleans, empty collections for List/Set/Map. Unstubbed calls don't throw — they silently return defaults.

MediumWhen should you use @InjectMocks?
+

@InjectMocks tells Mockito to construct the class under test and inject all @Mock and @Spy fields into it (by constructor, setter, or field injection). Use it for convenience, but be careful: if injection fails silently, the field stays null and tests give misleading NullPointerExceptions.

MediumWhat is the difference between thenReturn and thenThrow?
+

when(method).thenReturn(value) makes the mock return the value. when(method).thenThrow(new RuntimeException()) makes it throw. Use thenThrow to test error paths.

HardHow does Mockito create mock objects at the bytecode level?
+

Mockito uses ByteBuddy to generate a subclass (or proxy) of the target class at runtime. The generated class overrides every method to: record the call arguments, check for matching stubs, return the stubbed value (or default), and add the call to the invocation log for verify(). This is why Mockito requires the JVM to allow dynamic class loading — on JDK 21+ it needs the byte-buddy-agent.jar dynamically attached.

📝 Quiz — 5 questions

Question 1 of 5
What does @Mock create?
Question 2 of 5
What does when(repo.hasFiled(pan)).thenReturn(false) do?
Question 3 of 5
What does verify(repo, never()).save(any()) assert?
Question 4 of 5
What is the difference between @Mock and @Spy?
Question 5 of 5
Which annotation enables Mockito in a JUnit 5 test class?
0
/ 5
Quiz complete!

Next: Integration Tests with Testcontainers →

⚠️ Common mistakes

Mixing matchers and raw values in verify()
verify(notifier).send("PAN001", anyString()) mixes a raw value with a matcher. Mockito requires all arguments to use matchers or none. Fix: verify(notifier).send(eq("PAN001"), anyString()).
Stubbing void methods with when()
when(repo.save(x)) won't compile for void methods. Use doNothing().when(repo).save(any()) or doThrow().when(repo).save(any()).
Verifying the wrong object
verify(calculator) when you meant verify(repository) silently passes if calculator has any matching method. Always verify the object you care about.
Over-mocking — mocking the class under test
Mock the dependencies, not the class you're testing. If you mock TaxFilingService itself there's nothing left to test.

✅ Key takeaways

  • @Mock creates a fake; @Spy wraps a real object; @ExtendWith(MockitoExtension.class) enables both
  • when(mock.method()).thenReturn(value) stubs a response (Arrange step)
  • verify(mock, times(1)).method(args) checks interactions (Assert step)
  • never() asserts a method was not called — critical for error path tests
  • Mix raw values and matchers with eq() — never mix matchers and raw values in the same call
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

From mocked services to production-grade Java

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →