Mocking with Spring

Hi folks, Been diving deep into Spring Testing lately, and today I'm sharing my learnings about mocking in Spring. I've noticed many developers struggle with this, so let's break it down in a simple way.

What is Mocking?

Mocking is our way of creating objects that simulate the behaviour of real objects during testing. Rather brilliant, eh? When testing complex systems, we don't want to call actual databases or external services - that's where mocking comes in handy.

A typical Spring test setup with mocking involves two main components:

  1. Mockito - the brilliant mocking framework that Spring plays nicely with
  2. Spring Test context - Spring's testing support that lets us write integration tests

Terminology:

What is @Mock?

@Mock creates a mock implementation for the interfaces or classes. It's like having a stunt double for your actual implementation - looks the same but doesn't do the real work.

What is @MockBean?

@MockBean is Spring Boot's way of adding mock objects into the Spring application context. Brilliant for integration testing where you want to mock just one bean and test the others.

What is @InjectMocks?

@InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock annotations into this instance.

Let's look at a dead simple example:

        
@SpringBootTest
class UserServiceTest {
    @MockBean
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Test
    void shouldReturnUser() {
        // Given
        User mockUser = new User("John");
        when(userRepository.findById(1L)).thenReturn(Optional.of(mockUser));

        // When
        User result = userService.getUser(1L);

        // Then
        assertEquals("John", result.getName());
    }
}
        
    

Pretty straightforward, isn't it? The test above shows how we can mock our repository layer whilst testing the service layer. If everything works as promised, we can verify our business logic without touching the database.

Today's testing frameworks make mocking quite simple, but remember - with great power comes great responsibility. Don't mock everything just because you can. Mock what you must, test what you should.

Next time, I'll share some advanced mocking patterns I've discovered while working with Spring. Until then, happy testing!

Comments

Popular posts from this blog

MDK Hospital opened in Horana

Disable single quote Within Forms

My Docker learning short notes