首页  编辑  

Java Mockito mock 被测试方法内新建第三方对象的方法的方法

Tags: /Java/   Date Created:
在Java, mockito内,如果要mock被测试方法内创建的第三方对象的方法,可以使用mockedConstrution。
例如,被测试类 CheckoutService,要测试的方法purchaseProduct内,有一个第三方的的对象 paymentProcessor,如果我们想mock它的chargeCustomer方法,参考下面的代码:

// 被测试类
public class CheckoutService {
 
  public BigDecimal purchaseProduct(String productName, String customerId) {
    // any arbitrary implementation
    PaymentProcessor paymentProcessor = new PaymentProcessor();
 
    return paymentProcessor.chargeCustomer(customerId, BigDecimal.TEN);
  }
}
测试代码:
class CheckoutServiceTest {

  @Test
  void mockObjectConstruction() {
    try (MockedConstruction<PaymentProcessor> mocked = Mockito.mockConstruction(PaymentProcessor.class,
      (mock, context) -> {
        // further stubbings ...
        when(mock.chargeCustomer(anyString(), any(BigDecimal.class))).thenReturn(BigDecimal.TEN);
      })) {

      CheckoutService cut = new CheckoutService();

      BigDecimal result = cut.purchaseProduct("MacBook Pro", "42");

      assertEquals(BigDecimal.TEN, result);
    }
  }
}
注意需要引入依赖包:
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <scope>test</scope>
</dependency>
并且不支持安卓。
上面的方法,等价于 JMock下的:
MockUp<PaymentProcessor> mocked = new MockUp<PaymentProcessor>() {
	@Mock
        public BigDecimal purchaseProduct(String productName, String customerId) {
     		return BigDecimal.TEN;
	}
}