🌟 Day 12 of #100DaysOfCode: Diving into Mockito! 🌟

Hey Invaders! 👽

#100daysofcode day 12, I continued working on my JUnit course and started section 8: Mockito. Today was all about Mockito magic! 🧙‍♂️ I learned how to integrate Mockito into my projects, injecting dependencies, and using annotations like @InjectMocks and @Mock.

Here's a quick rundown of what I explored:

  • Creating mock objects to simulate dependencies.

  • Stubbing methods using when() and built-in matchers like any().

  • Verifying method calls using verify().

  • Exception stubbing for handling specific scenarios.

Here is a code snippet on how to test dependency injections and how I created the tests using mockito when!

@ExtendWith(MockitoExtension.class)
public class UserServiceTest {

    @InjectMocks //the service that takes the dependency injections
    UserServiceImpl userService;

    @Mock //the dependency that gets injected
    UsersRepository usersRepository;

    @Mock
    EmailVerificationServiceImpl emailVerificationService;

    String firstName;
    String lastName;
    String email;
    String password;
    String repeatPassword;

    @BeforeEach
    void init() {
        userService = new UserServiceImpl(usersRepository); // Inject mock repository
        firstName = "ari";
        lastName = "vanegas";
        email = "[email protected]";
        password = "1234567";
        repeatPassword = "1234567";
    }

    @DisplayName("If save() method causes RuntimeException, a UserServiceException is thrown")
    @Test
    void testCreateUser_whenSaveMethodThrowsException_thenThrowsUserServiceException(){
        // Arrange: Mock the repository to throw a RuntimeException when saving
        when(usersRepository.save(any(User.class))).thenThrow(RuntimeException.class);

        // Act & Assert: Ensure that a UserServiceException is thrown
        assertThrows(UserServiceException.class, () -> {
            userService.createUser(firstName, lastName, email, password, repeatPassword);
        }, "should have thrown UserServiceException instead");
    }
}

Mockito is a powerful tool for testing, and I'm excited to leverage it for more robust and effective unit tests! For more on what I implemented for today you can checkout my Git Hub! 

Stay tuned for more updates on my #100DaysOfCode journey. Happy coding! 💻✨

Reply

or to participate.