free geoip
76

Testing with Mockito in Java Android Apps

Unit testing is an essential part of developing robust and reliable Android applications. In Java-based Android development, Mockito stands out…

Unit testing is an essential part of developing robust and reliable Android applications. In Java-based Android development, Mockito stands out as one of the most popular and powerful libraries for creating mock objects and writing clean, maintainable unit tests. This article will guide you through the basics of using Mockito in Java Android apps, from setting up dependencies to writing practical test cases.

Testing with Mockito in Java Android

Why Use Mockito in Android?

Mockito simplifies testing by allowing you to create mock objects for dependencies, so you can focus on testing the behavior of your classes without relying on real implementations. This is particularly useful when dealing with network calls, database operations, or complex logic that shouldn’t be executed during unit tests.

Setting Up Mockito in Your Android Project

To begin using Mockito in your Android Java project, you need to add the following dependencies to your build.gradle file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// For unit testing with Mockito
testImplementation 'org.mockito:mockito-core:5.3.1'
// Optional: For Android-specific integration
androidTestImplementation 'org.mockito:mockito-android:5.3.1'
// For unit testing with Mockito testImplementation 'org.mockito:mockito-core:5.3.1' // Optional: For Android-specific integration androidTestImplementation 'org.mockito:mockito-android:5.3.1'
// For unit testing with Mockito
testImplementation 'org.mockito:mockito-core:5.3.1'

// Optional: For Android-specific integration
androidTestImplementation 'org.mockito:mockito-android:5.3.1'

You also need to include JUnit for running the tests:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
testImplementation 'junit:junit:4.13.2'
testImplementation 'junit:junit:4.13.2'
testImplementation 'junit:junit:4.13.2'

Creating a Simple Example

Let’s consider a UserRepository class that interacts with a UserService:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class UserRepository {
private final UserService userService;
public UserRepository(UserService userService) {
this.userService = userService;
}
public String getUsername(int userId) {
return userService.fetchUser(userId).getUsername();
}
}
public class UserRepository { private final UserService userService; public UserRepository(UserService userService) { this.userService = userService; } public String getUsername(int userId) { return userService.fetchUser(userId).getUsername(); } }
public class UserRepository {
    private final UserService userService;

    public UserRepository(UserService userService) {
        this.userService = userService;
    }

    public String getUsername(int userId) {
        return userService.fetchUser(userId).getUsername();
    }
}

Suppose UserService makes a network call that we want to avoid during testing. We can mock it using Mockito.

Writing Unit Test with Mockito

Here’s a unit test using Mockito to mock UserService:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@RunWith(MockitoJUnitRunner.class)
public class UserRepositoryTest {
@Mock
UserService userService;
@InjectMocks
UserRepository userRepository;
@Test
public void testGetUsername_returnsCorrectUsername() {
User mockUser = new User("mock_user");
Mockito.when(userService.fetchUser(1)).thenReturn(mockUser);
String result = userRepository.getUsername(1);
assertEquals("mock_user", result);
}
}
@RunWith(MockitoJUnitRunner.class) public class UserRepositoryTest { @Mock UserService userService; @InjectMocks UserRepository userRepository; @Test public void testGetUsername_returnsCorrectUsername() { User mockUser = new User("mock_user"); Mockito.when(userService.fetchUser(1)).thenReturn(mockUser); String result = userRepository.getUsername(1); assertEquals("mock_user", result); } }
@RunWith(MockitoJUnitRunner.class)
public class UserRepositoryTest {

    @Mock
    UserService userService;

    @InjectMocks
    UserRepository userRepository;

    @Test
    public void testGetUsername_returnsCorrectUsername() {
        User mockUser = new User("mock_user");
        Mockito.when(userService.fetchUser(1)).thenReturn(mockUser);

        String result = userRepository.getUsername(1);

        assertEquals("mock_user", result);
    }
}

In this test:

  • @Mock creates a mock object of UserService.
  • @InjectMocks injects the mock into the UserRepository instance.
  • when().thenReturn() sets up the behavior of the mock.
  • assertEquals() verifies that the returned result matches the expected username.

Common Mockito Features

  • verify() – Verifies whether a method was called on a mock.
  • any() – Accepts any value of a specific type.
  • doThrow() – Simulates exceptions in method calls.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
verify(userService).fetchUser(anyInt());
verify(userService).fetchUser(anyInt());
verify(userService).fetchUser(anyInt());

This ensures that fetchUser was called with any integer.

Best Practices

  1. Keep tests small and focused.
  2. Use meaningful mock behavior.
  3. Avoid mocking classes you own — use real implementations when possible.
  4. Run tests frequently during development.

Mockito + LiveData or ViewModel Testing

When testing ViewModel classes in Android that use LiveData, Mockito can be used in combination with InstantTaskExecutorRule to execute background tasks synchronously.

Learn More

Mockito is part of a broader ecosystem of tools for Android testing. To explore more advanced scenarios and best practices, the official Mockito documentation provides comprehensive coverage.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *