522

有没有办法使用 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);
}
4

5 回答 5

829

要直接回答您的问题,是的,您可以模拟某些方法而不模拟其他方法。这称为部分模拟。有关更多信息,请参阅有关部分模拟的 Mockito 文档

对于您的示例,您可以在测试中执行以下操作:

Stock stock = mock(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
when(stock.getValue()).thenCallRealMethod();  // Real implementation

在这种情况下,每个方法实现都会被模拟,除非thenCallRealMethod()when(..)子句中指定。

也有可能使用spy而不是mock

Stock stock = spy(Stock.class);
when(stock.getPrice()).thenReturn(100.00);    // Mock implementation
when(stock.getQuantity()).thenReturn(200);    // Mock implementation
// All other method call will use the real implementations

在这种情况下,所有方法实现都是真实的,除非您使用when(..).

when(Object)当您像上一个示例一样使用 spy时,有一个重要的陷阱。将调用真正的方法(因为stock.getPrice()之前when(..)在运行时进行了评估)。如果您的方法包含不应调用的逻辑,这可能是一个问题。您可以像这样编写前面的示例:

Stock stock = spy(Stock.class);
doReturn(100.00).when(stock).getPrice();    // Mock implementation
doReturn(200).when(stock).getQuantity();    // Mock implementation
// All other method call will use the real implementations

另一种可能是使用org.mockito.Mockito.CALLS_REAL_METHODS,例如:

Stock MOCK_STOCK = Mockito.mock( Stock.class, CALLS_REAL_METHODS );

这将未存根的调用委托给实际实现。


但是,对于您的示例,我相信它仍然会失败,因为实现getValue()依赖于quantityand price,而不是getQuantity()and getPrice(),这是您所嘲笑的。

另一种可能性是完全避免模拟:

@Test
public void getValueTest() {
    Stock stock = new Stock(100.00, 200);
    double value = stock.getValue();
    assertEquals("Stock value not correct", 100.00*200, value, .00001);
}
于 2013-02-20T01:02:37.010 回答
161

通过Spy in mockito也支持类的部分模拟

List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls real methods
spy.add("one");
spy.add("two");

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

检查1.10.192.7.22文档以获取详细说明。

于 2013-05-24T06:52:46.820 回答
41

根据文档

Foo mock = mock(Foo.class, CALLS_REAL_METHODS);

// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();

when(mock.getSomething()).thenReturn(fakeValue);

// now fakeValue is returned
value = mock.getSomething();
于 2015-09-01T13:30:48.583 回答
19

你想要的是org.mockito.Mockito.CALLS_REAL_METHODS根据文档:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

因此,您的代码应如下所示:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    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, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

调用Stock stock = mock(Stock.class);如下org.mockito.Mockito.mock(Class<T>)所示:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

该值的文档RETURNS_DEFAULTS告诉:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */
于 2016-02-19T11:47:16.753 回答
4

如上面的答案所述,使用 Mockito 的 spy 方法进行部分模拟可能是您问题的解决方案。在某种程度上,我同意,对于您的具体用例,模拟数据库查找可能更合适。根据我的经验,这并不总是可能的——至少在没有其他解决方法的情况下并非如此——我认为这非常麻烦或至少很脆弱。请注意,部分模拟不适用于 Mockito 的盟友版本。您至少使用了 1.8.0。

我会为原始问题写一个简单的评论,而不是发布这个答案,但 StackOverflow 不允许这样做。

还有一件事:我真的无法理解,这里有很多次被问到的问题都会得到“你为什么要这样做”的评论,而至少没有试图理解这个问题。尤其是当需要部分模拟时,我可以想象有很多用例在哪里有用。这就是为什么来自 Mockito 的人提供了该功能。这个特性当然不应该被过度使用。但是当我们谈论无法以非常复杂的方式建立的测试用例设置时,应该使用间谍。

于 2017-01-24T20:49:43.513 回答