使用 mockito 的 when() 配合 thenreturn() 即可设置模拟方法返回值。具体做法是先通过 @mock 注解创建模拟对象,然后在测试代码中调用 when(mock.method()).thenreturn(value) 来定义行为,这样当测试运行到该模拟方法时就会返回预设值。

如何为接口方法配置固定返回值
直接回答:在测试类中声明一个被 @Mock 标注的接口实例,然后使用 when() 包裹对该实例的方法调用,并用 thenReturn() 指定期望返回的具体数值或对象。

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@Test
void shouldReturnUserWhenIdExists() {
// 设置模拟行为:当调用 findById(1) 时返回 User 对象
when(userRepository.findById(1)).thenReturn(new User(1, "Alice"));
// 执行被测逻辑
User result = userRepository.findById(1);
// 验证结果
assertEquals("Alice", result.getName());
}
}
如何处理多个不同参数的返回值
直接回答:针对同一个模拟对象的不同参数组合,可以连续编写多条 when().thenReturn() 语句,或者使用 doReturn().when() 语法来处理 void 方法或更复杂的场景,确保每个参数映射都有对应的返回值定义。

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private PaymentGateway paymentGateway;
@Test
void shouldHandleDifferentPaymentMethods() {
// 为不同支付方式设置不同的返回值
when(paymentGateway.process("CREDIT_CARD")).thenReturn(true);
when(paymentGateway.process("PAYPAL")).thenReturn(false);
// 验证信用卡支付成功
boolean isCardSuccess = paymentGateway.process("CREDIT_CARD");
assertEquals(true, isCardSuccess);
// 验证 PayPal 支付失败
boolean isPaypalSuccess = paymentGateway.process("PAYPAL");
assertEquals(false, isPaypalSuccess);
}
}
当模拟方法抛出异常时会发生什么
直接回答:如果希望模拟方法在特定条件下抛出异常而不是返回正常值,可以使用 thenThrow() 替代 thenReturn(),这在测试错误处理逻辑时非常有用。

















