ChatGPT解决这个技术问题 Extra ChatGPT

使用 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);
}
你为什么想这么做?您应该测试该类(在这种情况下,根本不应该进行模拟),或者您应该在测试不同的类时模拟它(在这种情况下,没有功能)。为什么要进行部分模拟?
好的,这是真实事物的一个小例子。实际上,我试图通过传入人为的值来避免调用数据库,但我想验证其他方法是否可以正确处理这些人为的值。有一个更好的方法吗?
当然:将您的数据库调用移动到一个单独的类(域逻辑和数据库访问不应该在同一个类中;它们是两个不同的关注点),提取其接口,使用该接口从域逻辑类连接,并仅模拟测试时的界面。
我完全同意,如果不在这里上传大量代码(包括第三方库),很难解释整个画面。
你可能可以。但是,这并不是“更好的方法”:您的数据库代码是您希望对应用程序的其余部分隐藏的实现细节,甚至可能移动到不同的包中。您不希望每次更改后续语句时都必须重新编译域逻辑,对吗?

D
Dave Jarvis

要直接回答您的问题,是的,您可以模拟某些方法而不模拟其他方法。这称为部分模拟。有关详细信息,请参阅 the Mockito documentation on partial mocks

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

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

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

也有可能使用 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() 的实现依赖于 quantityprice,而不是您所嘲笑的 getQuantity()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);
}

我认为这个答案是错误的。您需要 SPY 对象的实例,而不是 MOCK 类。
@GaRRaPeTa 我会说间谍和嘲笑都是合理的选择。很难说哪种情况最适合这种情况,因为 OP 声明这是一个简化的示例。
public static <T> T spy(java.lang.Class<T> classToSpy) 仍然有我在 2016 年 9 月写的注释 @Incubating...如果您真的想使用部分模拟,则应在 instance 上调用 spy 方法
Stock stock = spy(Stock.class); 这似乎是错误的,spy 方法似乎只接受对象而不接受类。
+1 指出 doReturn(retval).when(spyObj).methodName(args)when(spyObj.methodName(args)).thenReturn(retval) 之间的区别
A
Abdull

通过 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 文档以获取详细说明。


e
ema

根据 docs

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();

感谢您演示如何设置一个模拟,其中所有方法都调用真正的实现,除了我需要从测试中控制的少数方法。
class NaughtyLinkedList extends LinkedList { public int size() { throw new RuntimeException("don't call me");} } @Test public void partialMockNaughtLinkedList(){ List mock = mock(NaughtyLinkedList.class, CALLS_REAL_METHODS); mock.add(new Object()); // this calls the real function when(mock.size()).thenReturn(2); // For whatever reason, this lines throws the RuntimeException. assertEquals(2,mock.size()); } 这不起作用。无论出于何种原因,当“when”被执行时,它实际上执行了应该被模拟的方法。代码:
问题是“何时”。 “何时”实际上会执行您想要部分模拟的东西。为了避免这种情况,有一个替代方法:doReturn()。请参阅 docs.mockito.googlecode.com/hg/1.9.5/org/mockito/… 处的 doReturn()
试图实现这个答案,发现 when(mock.getSomething()).thenReturn(fakeValue); 不起作用,而不得不使用 doReturn(fakeValue).when(mock).getSomething()
D
Dave Jarvis

根据文档,您想要的是 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.)
 */

很好发现...但是我能问一下您为什么这样使用 withSettings()... 吗?看起来 org.mockito.internal.stubbing.answers.CallsRealMethods() (例如)可能会完成这项工作......并且这个类的 javadoc 专门说它用于部分模拟......
另外...这里不会遇到其他答案遇到的问题:即 thenReturn 将实际执行该方法(这可能会导致问题,尽管在此示例中没有),因此 doReturn 在这种情况下更可取案子...?
k
kflGalore

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

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

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


我觉得这个答案部分是一种观点。请考虑编辑。
赞成为家庭中的新成员振作起来。无需在 -ve 区域中获取此内容,那里没有真正的技术错误或不正确的语言/语气。善待新成员。谢谢。