Mock objects and fixtures in Java: how to test faster and smarter

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why your Java tests break (and how to fix it)

\n\n

You wrote perfect code. The service works, the logic is flawless, and bugs only exist in other people's projects. But when you run the tests... There's a database connection error, an external API isn't responding, and in the third test there's a NullPointerException because the configuration didn't load correctly. Sound familiar?

\n\n

The problem is that classic tests depend on the external environment. Databases, REST services, file systems — all of this makes tests fragile, slow, and unpredictable. The solution is mock objects and fixtures. These aren't just buzzwords, but tools that turn chaos into order.

\n\n

In this article, we'll figure out how to properly use mocks and fixtures in Java tests with real examples. You'll learn how stub differs from mock, how to set up fixtures for complex scenarios, and why Mockito is your best friend. Let's go!

\n\n

Mock objects: simulation without pain

\n\n

What is a mock and why do you need it?

\n\n

A mock object is an imitation of a real component that behaves exactly as you tell it to. Instead of spinning up a database or calling an external API, you create a "fake" that returns predefined data.

\n\n

Imagine: you're testing a service that sends email notifications. For a real test, you'd need to spin up a mail server, configure SMTP, check the queue... But with a mock object, you simply verify that the service called the send method with the correct parameters. Fast, clean, controllable.

\n\n

Mock vs Stub: what's the difference?

\n\n

Beginners often confuse these concepts. Let's set the record straight:

\n\n
    \n
  • Stub — returns fixed data. You say: "When the getUser() method is called, return a User object with the name 'John'". A stub does not verify how many times it was called.
  • \n
  • Mock — not only returns data but also verifies behavior. You can say: "Make sure the sendEmail() method was called exactly once with a specific address".
  • \n
\n\n

Simply put: a stub is "give me data", a mock is "give me data and check how I'm being used". In practice, mock objects are used more often because they give you more control.

\n\n

Writing your first mock with Mockito

\n\n

Mockito is the most popular library for mocks in Java. It integrates with JUnit 5 and Spring Boot, and the syntax is so simple you'll memorize it in five minutes.

\n\n

Let's say you have an OrderService that depends on an OrderRepository. Instead of a real repository, we'll create a mock:

\n\n
import static org.mockito.Mockito.*;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.Mock;\nimport org.mockito.junit.jupiter.MockitoExtension;\nimport org.junit.jupiter.api.extension.ExtendWith;\n\n@ExtendWith(MockitoExtension.class)\npublic class OrderServiceTest {\n\n    @Mock\n    private OrderRepository orderRepository;\n\n    @Test\n    void testCreateOrder() {\n        // Create a mock object\n        OrderService orderService = new OrderService(orderRepository);\n        \n        // Configure mock behavior\n        when(orderRepository.save(any(Order.class)))\n            .thenReturn(new Order(1L, "test@example.com", 100.0));\n        \n        // Call the method under test\n        Order result = orderService.createOrder("test@example.com", 100.0);\n        \n        // Verify the result\n        assertThat(result.getId()).isEqualTo(1L);\n        // Verify that the save method was called exactly once\n        verify(orderRepository, times(1)).save(any(Order.class));\n    }\n}
\n\n

In this example, we:

\n
    \n
  • Created a mock for OrderRepository using the @Mock annotation.
  • \n
  • Configured that when save() is called, a pre-created order should be returned.
  • \n
  • Verified

Blogs

Book Recommendations