代码之家  ›  专栏  ›  技术社区  ›  Matteo NNZ

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

  •  3
  • Matteo NNZ  · 技术社区  · 7 年前

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

    .price() pricingSession (类型 PricingSessionImpl )调用了以下方法:

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

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

    有人能告诉我调试这个问题的好方向吗?请注意,我已经检查了网络上已经出现的关于这个主题的多个问题/答案,但到目前为止没有发现任何对我的具体案例有用的东西。
    如果您需要查看代码中的更多内容,请毫不犹豫地询问。

    1 回复  |  直到 7 年前
        1
  •  4
  •   MatF    7 年前

    要使间谍真正被使用,调用 price(listOfProductsToPrice) 需要去侦察的地方 spyPricingSession

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