The when
method in Mockito is used to enable stubbing of methods. Stubbing allows you to specify what a method should return when it is called. This is useful for setting up mocks to return specific values or behaviors during testing.
Table of Contents
- Introduction
when
Method Syntax- Examples
- Basic Usage
- Stubbing with Different Return Values
- Stubbing with Exceptions
- Real-World Use Case
- Conclusion
Introduction
Mockito is a popular library in Java for creating mock objects. The when
method is used to define the behavior of these mock objects. By using when
, you can specify what a method should return or do when it is called during a test. This helps you isolate the unit of code being tested by controlling the behavior of its dependencies.
when Method Syntax
static <T> OngoingStubbing<T> when(T methodCall)
Parameters:
methodCall
: The method call on the mock object that you want to stub.
Returns:
- An
OngoingStubbing<T>
object that allows you to specify the return value or behavior for the stubbed method.
Examples
Basic Usage
Stub a method to return a specific value.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BasicStubbingTest {
@Test
void testWhen() {
UserService mockUserService = mock(UserService.class);
// Stub the getUserDetails method to return "Mock user details" when called with "123"
when(mockUserService.getUserDetails("123")).thenReturn("Mock user details");
String details = mockUserService.getUserDetails("123");
assertEquals("Mock user details", details);
}
}
class UserService {
public String getUserDetails(String userId) {
return "Real user details for " + userId;
}
}
Stubbing with Different Return Values
Stub a method to return different values based on the input.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DifferentReturnValuesTest {
@Test
void testWhenWithDifferentReturnValues() {
UserService mockUserService = mock(UserService.class);
// Stub the getUserDetails method to return different values based on the input
when(mockUserService.getUserDetails("123")).thenReturn("User details for 123");
when(mockUserService.getUserDetails("456")).thenReturn("User details for 456");
assertEquals("User details for 123", mockUserService.getUserDetails("123"));
assertEquals("User details for 456", mockUserService.getUserDetails("456"));
}
}
class UserService {
public String getUserDetails(String userId) {
return "Real user details for " + userId;
}
}
Stubbing with Exceptions
Stub a method to throw an exception when called.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class StubbingWithExceptionsTest {
@Test
void testWhenWithException() {
UserService mockUserService = mock(UserService.class);
// Stub the getUserDetails method to throw an exception when called with "123"
when(mockUserService.getUserDetails("123")).thenThrow(new RuntimeException("User not found"));
assertThrows(RuntimeException.class, () -> {
mockUserService.getUserDetails("123");
});
}
}
class UserService {
public String getUserDetails(String userId) {
return "Real user details for " + userId;
}
}
Real-World Use Case
Testing a Service with Dependency
In a real-world scenario, you might have a UserService
class that depends on a UserRepository
. Using Mockito, you can stub the UserRepository
to control its behavior during the test.
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
}
interface UserRepository {
User findUserById(String id);
}
class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public String getUserName(String userId) {
User user = userRepository.findUserById(userId);
return user != null ? user.getName() : null;
}
}
public class UserServiceTest {
@Test
void testGetUserName() {
// Given
UserRepository mockUserRepository = mock(UserRepository.class);
// Stub the findUserById method to return a specific user
when(mockUserRepository.findUserById("123")).thenReturn(new User("123", "John Doe"));
UserService userService = new UserService(mockUserRepository);
// When
String userName = userService.getUserName("123");
//Then
assertEquals("John Doe", userName);
verify(mockUserRepository).findUserById("123");
}
}
In this example, the UserServiceTest
class uses Mockito’s when
method to stub the findUserById
method of the UserRepository
interface. The test then verifies that the UserService
behaves as expected when the stubbed method is called.
Output
Conclusion
The when
method in Mockito is used for stubbing methods on mock objects. By using when
, you can define the behavior of methods when they are called during a test. This helps you isolate the unit of code being tested and ensure that your tests are reliable and focused.