相关疑难解决方法(0)

使用Mockito来模拟一些方法而不是其他方法

有没有办法,使用Mockito来模拟一个类中的某些方法,而不是其他方法?

例如,在这个(公认的设计)Stock类中我想模拟getPrice()和getQuantity()返回值(如下面的测试片段所示),但我希望getValue()执行在Stock中编码的乘法类

public class Stock {
  private final double price;
  private final int quantity;

  Stock(double price, int quantity) {
    this.price = price;
    this.quantity = quantity;
  }

  public double getPrice() {
    return price;
  }

  public int getQuantity() {
    return quantity;
  }
  public double getValue() {
    return getPrice() * getQuantity();
  }

  @Test
  public void getValueTest() {
    Stock stock = mock(Stock.class);
    when(stock.getPrice()).thenReturn(100.00);
    when(stock.getQuantity()).thenReturn(200);
    double value = stock.getValue();
    // Unfortunately the following assert fails, because the mock Stock getValue() method does not perform the …
Run Code Online (Sandbox Code Playgroud)

java mocking mockito

354
推荐指数
4
解决办法
36万
查看次数

标签 统计

java ×1

mocking ×1

mockito ×1