0
0
JUnittesting~5 mins

Mockito dependency setup in JUnit

Choose your learning style9 modes available
Introduction

Mockito helps us test code by creating fake objects. Setting it up means adding the right tools to your project so you can use Mockito easily.

When you want to test a class that uses other classes without running the real ones.
When you need to check how your code behaves with different responses from other parts.
When you want to write tests faster by avoiding complex setup of real objects.
Syntax
JUnit
For Maven projects, add this to your pom.xml:

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>5.4.0</version>
  <scope>test</scope>
</dependency>

For Gradle projects, add this to your build.gradle:

testImplementation 'org.mockito:mockito-core:5.4.0'

Use the latest stable version of Mockito for best features and fixes.

Scope 'test' means Mockito is only used during testing, not in the final app.

Examples
This is how you add Mockito to a Maven project.
JUnit
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>5.4.0</version>
  <scope>test</scope>
</dependency>
This is how you add Mockito to a Gradle project.
JUnit
testImplementation 'org.mockito:mockito-core:5.4.0'
Sample Program

This test shows Mockito working after setup. It creates a fake list, tells it to return 3 when size() is called, and checks that it does.

JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;

public class MockitoSetupTest {

    @Test
    public void testMockList() {
        // Create a mock List
        List<String> mockedList = mock(List.class);

        // Use the mock object
        when(mockedList.size()).thenReturn(3);

        // Verify the size method returns 3
        assertEquals(3, mockedList.size());
    }
}
OutputSuccess
Important Notes

Make sure your test framework (like JUnit 5) is also set up correctly.

Mockito works best with Java 8 or higher.

Summary

Mockito dependency setup means adding Mockito to your project files.

This setup lets you create fake objects for easier testing.

Use the correct version and scope for smooth testing.