使用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 Stock.getValue() calculation code.
assertEquals("Stock value not correct", 100.00*200, value, .00001);
}