Mockito interview questions test Java mocking skill across mocks, stubs, verification, argument matchers, captors, spies, exceptions, and test design trade-offs.
45 questions with answersKey Takeaways
Mockito is a Java mocking framework used to isolate dependencies in unit tests. In interviews, Mockito questions check whether you know when to mock, how to stub behavior, how to verify interactions, and when mocks make a test weaker instead of stronger.
Watch: Mockito Tutorial
Video: Mockito Tutorial (Java Brains, YouTube)
Test yourself and earn a certificate
6 quick questions. Score 70%+ to download your Mockito certificate.
Start here. These are the definitions and first-principle checks that open most rounds.
mock is the part of Mockito that controls the shape of the work: what input is accepted, what output is expected, and where the risk sits.
In Java service tests that isolate dependencies, mock has a normal path, an edge case, and evidence such as failing and passing unit tests with verified collaboration where needed.
For mock, the practical check is whether a JUnit test with mocks, stubs, verification, and clear assertions reflects the intended behavior and whether failing and passing unit tests with verified collaboration where needed confirms it.
Watch a deeper explanation
Video: Mockito Tutorial (Java Brains, YouTube)
stub matters in Mockito because it changes the design choice, the failure mode, or the evidence that confirms the result.
stub has an owner, a failure mode, and a release check. Misunderstanding it can break ownership, behavior, or validation before release.
stub becomes useful when it changes a real choice: safer design, faster execution, clearer ownership, or better failure detection.
verify is not just vocabulary. In Mockito, it tells you which layer owns the behavior and which test or metric proves it is working.
verify maps to a JUnit test with mocks, stubs, verification, and clear assertions, so the concept is tied to a concrete artifact instead of a generic definition.
The main risk with verify is tests that mock too much and no longer prove real behavior; detection of that risk is part of the technical substance.
when thenReturn sets a boundary in Mockito: the artifact it affects, the behavior inside that boundary, and the consequence when it is wrong.
when thenReturn usually has a trade-off: what it makes easier, what it makes harder, and how the final choice is verified.
when thenReturn connects one concrete artifact, one measurable signal, and one reason the simpler option may not be enough.
| Answer part | What to say | Evidence to mention |
|---|---|---|
| Definition | when thenReturn in one direct sentence. | Official docs or course material |
| Use case | The work where it changes a decision. | Dataset, model, query, dashboard, or pipeline |
| Risk | What breaks when it is misunderstood. | Metric, log, test result, or review note |
thenThrow is a decision point in Mockito. The decision depends on fit, risk, operational cost, and the signal that would change the choice.
The final check for thenThrow comes from failing and passing unit tests with verified collaboration where needed, not a vague claim that the solution works.
In day-to-day work, thenThrow is judged by the result it protects: correctness, reliability, maintainability, cost, security, or user impact.
Watch a deeper explanation
Video: Mockito Tutorial for Beginners (in28minutes, YouTube)
ArgumentCaptor is the part of Mockito that controls the shape of the work: what input is accepted, what output is expected, and where the risk sits.
In Java service tests that isolate dependencies, ArgumentCaptor has a normal path, an edge case, and evidence such as failing and passing unit tests with verified collaboration where needed.
ArgumentCaptor has a boundary, behavior inside that boundary, and evidence outside it.
argument matchers matters in Mockito because it changes the design choice, the failure mode, or the evidence that confirms the result.
argument matchers has an owner, a failure mode, and a release check. Misunderstanding it can break ownership, behavior, or validation before release.
argument matchers is worth discussing only if it changes an action: what to build, what to test, what to monitor, or what to avoid.
@Mock is not just vocabulary. In Mockito, it tells you which layer owns the behavior and which test or metric proves it is working.
@Mock maps to a JUnit test with mocks, stubs, verification, and clear assertions, so the concept is tied to a concrete artifact instead of a generic definition.
The useful distinction for @Mock is where responsibility sits: code, data, configuration, platform, process, or owner.
@InjectMocks sets a boundary in Mockito: the artifact it affects, the behavior inside that boundary, and the consequence when it is wrong.
@InjectMocks usually has a trade-off: what it makes easier, what it makes harder, and how the final choice is verified.
@InjectMocks often fails quietly, so the validation should be observable through failing and passing unit tests with verified collaboration where needed.
MockitoExtension is a decision point in Mockito. The decision depends on fit, risk, operational cost, and the signal that would change the choice.
The final check for MockitoExtension comes from failing and passing unit tests with verified collaboration where needed, not a vague claim that the solution works.
MockitoExtension is specific: where it applies, where it does not, and what changes the decision.
spy is the part of Mockito that controls the shape of the work: what input is accepted, what output is expected, and where the risk sits.
In Java service tests that isolate dependencies, spy has a normal path, an edge case, and evidence such as failing and passing unit tests with verified collaboration where needed.
spy connects theory to delivery when the explanation includes input, output, owner, risk, and proof.
doReturn matters in Mockito because it changes the design choice, the failure mode, or the evidence that confirms the result.
doReturn has an owner, a failure mode, and a release check. Misunderstanding it can break ownership, behavior, or validation before release.
doReturn goes beyond definition when it includes the operating constraint and verification step.
mocking final classes is not just vocabulary. In Mockito, it tells you which layer owns the behavior and which test or metric proves it is working.
mocking final classes maps to a JUnit test with mocks, stubs, verification, and clear assertions, so the concept is tied to a concrete artifact instead of a generic definition.
mocking final classes is tied to the problem it solves, not just the tool or syntax that exposes it.
Watch a deeper explanation
Video: Mockito in JUnit 5 (Dan Vega, YouTube)
reset sets a boundary in Mockito: the artifact it affects, the behavior inside that boundary, and the consequence when it is wrong.
reset usually has a trade-off: what it makes easier, what it makes harder, and how the final choice is verified.
The decision around reset should be reversible or at least measurable, especially when tests that mock too much and no longer prove real behavior is possible.
strict stubs is a decision point in Mockito. The decision depends on fit, risk, operational cost, and the signal that would change the choice.
The final check for strict stubs comes from failing and passing unit tests with verified collaboration where needed, not a vague claim that the solution works.
strict stubs needs both the normal path and the edge case that breaks it.
These questions test whether you can apply the topic to real data, real code, and messy constraints.
mocking a repository starts with the goal, input, owner, and expected result, then moves through the smallest change that can be reviewed and tested.
mocking a repository needs a quick validation path: what runs, what output is expected, and what result makes the task complete.
mocking a repository is complete only when the result is visible in failing and passing unit tests with verified collaboration where needed and the next owner can repeat the check.
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock UserRepository repo;
@InjectMocks UserService service;
@Test
void returnsUserName() {
when(repo.findName(7L)).thenReturn("Asha");
assertEquals("Asha", service.nameFor(7L));
}
}Handle stubbing exceptions by separating setup, execution, validation, and cleanup. That prevents the answer from sounding like a command list.
stubbing exceptions often affects speed, safety, readability, cost, or ownership, depending on the environment.
The safe path for stubbing exceptions is small scope, known baseline, controlled change, and a rollback or correction option.
Start verifying a call with a known baseline. Record the current behavior, make one controlled change, then compare the result against failing and passing unit tests with verified collaboration where needed.
The main failure risk for verifying a call is tests that mock too much and no longer prove real behavior, so detection and prevention are part of the technical answer.
For verifying a call, the important artifact is a JUnit test with mocks, stubs, verification, and clear assertions; without it, the task is just activity without proof.
using argument captor depends on a JUnit test with mocks, stubs, verification, and clear assertions; the artifact makes the work concrete and testable.
using argument captor has a clear chain: task scope, execution, evidence inspection, and next action.
using argument captor preserves the user or system outcome first, then optimizes speed, cost, or convenience.
using matchers is delivery work, not trivia. The constraint, chosen approach, rollback path, and adjustment trigger all matter.
The judgment is in the fit: why this approach fits the role and which simpler alternative works in a smaller system.
The risk in using matchers is tests that mock too much and no longer prove real behavior, so the task needs an explicit prevention or detection step.
testing no interaction starts with the goal, input, owner, and expected result, then moves through the smallest change that can be reviewed and tested.
testing no interaction needs a quick validation path: what runs, what output is expected, and what result makes the task complete.
testing no interaction usually touches more than one layer, so separate input, processing, output, and ownership before changing anything.
Handle mocking void method by separating setup, execution, validation, and cleanup. That prevents the answer from sounding like a command list.
mocking void method often affects speed, safety, readability, cost, or ownership, depending on the environment.
mocking void method stops at a verified result, not a completed command or a passed local run.
Start using spy carefully with a known baseline. Record the current behavior, make one controlled change, then compare the result against failing and passing unit tests with verified collaboration where needed.
The main failure risk for using spy carefully is tests that mock too much and no longer prove real behavior, so detection and prevention are part of the technical answer.
using spy carefully needs a defined expected output, allowed side effects, and evidence source before execution.
testing service layer depends on a JUnit test with mocks, stubs, verification, and clear assertions; the artifact makes the work concrete and testable.
testing service layer has a clear chain: task scope, execution, evidence inspection, and next action.
testing service layer needs a negative case as well as the happy path, especially when the failure is expensive or hard to see.
avoiding over-verification is delivery work, not trivia. The constraint, chosen approach, rollback path, and adjustment trigger all matter.
The judgment is in the fit: why this approach fits the role and which simpler alternative works in a smaller system.
The simplest useful version of avoiding over-verification is the one that can be reviewed, repeated, and explained from the evidence.
Watch a deeper explanation
Video: Mocking with Mockito (Dan Vega, YouTube)
mocking external API client starts with the goal, input, owner, and expected result, then moves through the smallest change that can be reviewed and tested.
mocking external API client needs a quick validation path: what runs, what output is expected, and what result makes the task complete.
For mocking external API client, document the assumption that matters most because that is where follow-up failures usually start.
Handle testing retry logic by separating setup, execution, validation, and cleanup. That prevents the answer from sounding like a command list.
testing retry logic often affects speed, safety, readability, cost, or ownership, depending on the environment.
testing retry logic leaves a trace: test result, log line, metric, report, ticket, or review note.
Start testing fallback behavior with a known baseline. Record the current behavior, make one controlled change, then compare the result against failing and passing unit tests with verified collaboration where needed.
The main failure risk for testing fallback behavior is tests that mock too much and no longer prove real behavior, so detection and prevention are part of the technical answer.
The practical choice in testing fallback behavior is often between a quick local fix and a maintainable change that survives the next release.
using strict stubs depends on a JUnit test with mocks, stubs, verification, and clear assertions; the artifact makes the work concrete and testable.
using strict stubs has a clear chain: task scope, execution, evidence inspection, and next action.
using strict stubs becomes reliable when setup, execution, validation, and cleanup are separate and visible.
reviewing mock-heavy tests is delivery work, not trivia. The constraint, chosen approach, rollback path, and adjustment trigger all matter.
The judgment is in the fit: why this approach fits the role and which simpler alternative works in a smaller system.
reviewing mock-heavy tests controls blast radius by separating what changes now from what stays unchanged.
Advanced rounds test trade-offs, failure modes, and whether the decision can hold up under production pressure.
For test passes after product bug, reproduce the condition first, then isolate whether the fault sits in data, code, configuration, infrastructure, or process.
For Mockito, the evidence should come from failing and passing unit tests with verified collaboration where needed. That turns the answer from opinion into a traceable investigation.
test passes after product bug ends with a decision based on failing and passing unit tests with verified collaboration where needed, not a guess based on the first symptom.
Handle unused stubbing warning by protecting users first, collecting evidence second, and changing only the layer that the evidence points to.
unused stubbing warning can affect users, delivery, system reliability, security, or cost.
The first priority in unused stubbing warning is limiting impact while keeping enough evidence to prove the actual cause.
Do not guess at wanted but not invoked. Build a timeline, compare expected behavior with actual behavior, and test the narrowest fix before widening the change.
Prevention for wanted but not invoked can be test coverage, monitoring, documentation, a review rule, a config guardrail, or a runbook update, depending on the failure.
For wanted but not invoked, the useful split is symptom, cause, fix, validation, and prevention.
too many interactions verified is a decision under constraint: immediate mitigation, root-cause check, and the follow-up that prevents a repeat.
too many interactions verified rules out broad changes, hidden side effects, and fixes that cannot be verified in the same environment.
too many interactions verified is risky when tests that mock too much and no longer prove real behavior; the fix should address that risk directly.
spy hides design issue needs the production trade-offs up front: blast radius, rollback path, owner, validation signal, and communication plan.
Calm reasoning starts with the order of checks, not the final fix. The sequence matters because it keeps the investigation narrow and reversible.
The strongest mitigation for spy hides design issue is the smallest change that proves or disproves the suspected cause.
For matcher misuse, reproduce the condition first, then isolate whether the fault sits in data, code, configuration, infrastructure, or process.
For Mockito, the evidence should come from failing and passing unit tests with verified collaboration where needed. That turns the answer from opinion into a traceable investigation.
matcher misuse needs a timeline because order often reveals whether the issue came from data, code, configuration, or process.
Handle argument captor overuse by protecting users first, collecting evidence second, and changing only the layer that the evidence points to.
argument captor overuse can affect users, delivery, system reliability, security, or cost.
For argument captor overuse, communication matters because the owner, user impact, and next action must be clear before work spreads.
Do not guess at mocked class under test. Build a timeline, compare expected behavior with actual behavior, and test the narrowest fix before widening the change.
Prevention for mocked class under test can be test coverage, monitoring, documentation, a review rule, a config guardrail, or a runbook update, depending on the failure.
mocked class under test does not widen into a rewrite until the narrow failure has been reproduced and measured.
integration bug missed is a decision under constraint: immediate mitigation, root-cause check, and the follow-up that prevents a repeat.
integration bug missed rules out broad changes, hidden side effects, and fixes that cannot be verified in the same environment.
The prevention step for integration bug missed is concrete: a test, monitor, rule, review, runbook, or owner change.
void method exception needs the production trade-offs up front: blast radius, rollback path, owner, validation signal, and communication plan.
Calm reasoning starts with the order of checks, not the final fix. The sequence matters because it keeps the investigation narrow and reversible.
For void method exception, a rollback is useful only if it restores the failing behavior and has its own validation check.
For final class mock issue, reproduce the condition first, then isolate whether the fault sits in data, code, configuration, infrastructure, or process.
For Mockito, the evidence should come from failing and passing unit tests with verified collaboration where needed. That turns the answer from opinion into a traceable investigation.
final class mock issue is evaluated by blast radius, repeatability, customer impact, and confidence in the evidence.
Handle static method dependency by protecting users first, collecting evidence second, and changing only the layer that the evidence points to.
static method dependency can affect users, delivery, system reliability, security, or cost.
The best fix for static method dependency is one that reduces recurrence, not just the visible symptom.
Do not guess at flaky time dependency. Build a timeline, compare expected behavior with actual behavior, and test the narrowest fix before widening the change.
Prevention for flaky time dependency can be test coverage, monitoring, documentation, a review rule, a config guardrail, or a runbook update, depending on the failure.
For flaky time dependency, the hard part is separating real movement from measurement or environment noise.
legacy service hard to test is a decision under constraint: immediate mitigation, root-cause check, and the follow-up that prevents a repeat.
legacy service hard to test rules out broad changes, hidden side effects, and fixes that cannot be verified in the same environment.
legacy service hard to test preserves a record of what changed, why it changed, and what proved the change worked.
senior Mockito review needs the production trade-offs up front: blast radius, rollback path, owner, validation signal, and communication plan.
Calm reasoning starts with the order of checks, not the final fix. The sequence matters because it keeps the investigation narrow and reversible.
The final check for senior Mockito review is whether the same failure can be caught earlier next time.
Mockito overlaps with nearby topics, but each topic has a specific center of gravity. The table separates tool knowledge from judgment.
| Area | What it checks | Interview signal | Common miss |
|---|---|---|---|
| Mock | Fake dependency controlled by the test | Can isolate a unit | Mocking the class under test |
| Stub | Predefined return or exception | Can drive a specific branch | Stubbing unused behavior |
| Spy | Partial mock around a real object | Knows risk of partial mocking | Using spies to hide poor design |
| Fake | Working test implementation | Can replace external dependency | Confusing fake with mock |
Mockito interview scoring weight
The exact mix depends on role level and company stack.
Scale: Hyring editorial score for interview preparation, not an external benchmark.
Prepare by testing one Java service with a repository dependency. Stub the repository, call the service, assert the return, then verify only the interaction that matters.
Mockito interview prep flow
Strong answers definitions connects to a real project decision.
Strong Mockito answers show restraint. The best candidates know that a mock can make a test faster, but also easier to fool.
| Area | Weak answer | Strong answer |
|---|---|---|
| Mock choice | Mock everything. | Mock slow or external dependencies, not the behavior under test. |
| Verify | Verify every call. | Verify only collaboration that is part of the contract. |
| Matchers | Mix raw values and matchers. | Use matchers consistently and readably. |
| Design | Use spies everywhere. | Refactor hard-to-test design when spies hide the problem. |
Mockito evidence path
This path fits answers that need proof, not just a definition.
6 questions, about 4 minutes. Score 70% or higher to earn a shareable certificate.
Hyring's AI Video Interviewer helps candidates practice direct testing answers with examples, evidence, and follow-up reasoning.
Try AI interview prep