gpt4 book ai didi

java - Mockito.doReturn().when() 不起作用 - 单元测试继续调用原始方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:44 26 4
gpt4 key购买 nike

我正在为 SOAP API 编写单元测试,我需要在其中模拟某个方法的响应,但该方法一直被调用。

我的单元测试的(相关)代码如下:

import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;


public class PricingSessionTest{

@Test
public void testPricingOfStrategyWithCorrectFormat() throws Exception {

//[...other code...]
PricingSessionImpl pricingSession = new PricingSessionImpl(this.session);
PricingSessionImpl spyPricingSession = Mockito.spy(pricingSession);
Mockito.doReturn(myResult)
.when(spyPricingSession)
.send(
Mockito.any(MxML.class),
Matchers.eq(ACTION_PRICE),
Matchers.eq(TimeoutDuration),
Matchers.eq(TimeoutUnit)
);
List<PricingResult<?>> pricedProducts = pricingSession.price(listOfProductsToPrice);
}

在侦测对象pricingSession(类型PricingSessionImpl)的方法.price() 中,调用了以下方法:

protected List<MxDocument> send(MxML mxml, String action, long timeout, TimeUnit timeoutUnit) throws RequestException, RequestTimeoutException 

方法的实现在父类public abstract class AbstractPricingSession中(但方法本身不是abstract),可以在下面找到层级:

enter image description here

当我调试这个单元测试时,在某个时候我遇到了对我想要模拟的方法的调用:

List<MxDocument> documents = send(mxml, ACTION_PRICE, getTimeoutDuration(), getTimeoutUnit());

在这里,我希望我的 Mockito 返回给我 myResult,因为调用类中的方法 send() PricingSessionImpl 使用 MxML 类型的参数完成,然后是一个 String、一个 long 和一个 TimeUnit 这正是我传递给 .when() 的内容。

但是,该方法不断被调用。

任何人都可以指出调试此问题的正确方向吗?请注意,我已经检查了网络上已经存在的关于这个主题的多个问题/答案,但到目前为止没有发现任何对我的具体案例有帮助的东西。
如果您需要查看更多代码,请随时询问。

最佳答案

对于实际使用的 spy ,对 price(listOfProductsToPrice) 的调用需要转到被监视的实例 spyPricingSession

List<PricingResult<?>> pricedProducts = spyPricingSession.price(listOfProductsToPrice);

关于java - Mockito.doReturn().when() 不起作用 - 单元测试继续调用原始方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com