Skip to content
QuizMaker logoQuizMaker
Activity
Java Backend Interview Prep

No lessons available

CONTENTS

5. Testing: JUnit, Assertions, Mock, and Spy

Prepare for testing questions around JUnit lifecycle annotations and Mockito doubles.

Java Backend Interview Prep
1. Java Frameworks & Testing
May 29, 2026
21
A

JUnit Essentials

JUnit is a unit testing framework for Java. A unit test should verify one behavior in isolation and be fast enough to run often.

Common JUnit 4 annotations:

AnnotationPurpose
@TestMarks a test method
@BeforeRuns before each test
@AfterRuns after each test
@BeforeClassRuns once before all tests
@AfterClassRuns once after all tests

Common assertions include assertEquals, assertTrue, assertFalse, assertNull, and assertNotNull.

Mock vs Spy

A mock is a fully fake object. By default it does not call real behavior. A spy wraps a real object; unstubbed methods call real behavior.

Use mocks for external collaborators. Use spies carefully when partial real behavior is useful but you still need to stub a small part.

Interview Scenario Practice

Scenario 1: Mock External Payment Client

Scenario: Your service calls a payment gateway, but the unit test should not hit the real provider.

Strong answer: Mock the payment client and verify how the service behaves for success, failure, and timeout responses.

Why it works: Unit tests should be fast, deterministic, and isolated from external systems.

Common mistake: Calling real third-party services from unit tests, making tests slow and flaky.

Scenario 2: Mock vs Spy

Scenario: You need most real behavior from an object but want to stub one method.

Strong answer: A spy can wrap a real object and stub specific methods, while unstubbed methods still call real behavior.

Why it works: Spies are useful for partial substitution, but they should be used carefully because real methods may have side effects.

Common mistake: Using spies everywhere instead of designing smaller units with clear dependencies.

Scenario 3: Setup Repeated Before Tests

Scenario: Each test needs a fresh object with clean state.

Strong answer: Use per-test setup such as JUnit 4 @Before or JUnit 5 @BeforeEach.

Why it works: Fresh setup prevents one test's mutation from affecting another test.

Common mistake: Sharing mutable test state across tests and creating order-dependent failures.

Share this article

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava Backend Interview Prep
Quiz: JUnit and Mockito
8 questions8 min

0 comments

Please login to comment.
No comments yet.
Lesson 5 of 5 in 1. Java Frameworks & Testing
Previous in 1. Java Frameworks & Testing
4. Hibernate ORM Interview Essentials
Completed!
You've finished this course
Back to Java Backend Interview Prep
Back to moduleCategories