zoukankan      html  css  js  c++  java
  • Mockito when(...).thenReturn(...)和doReturn(...).when(...)的区别

    在Mockito中打桩(即stub)有两种方法when(...).thenReturn(...)和doReturn(...).when(...)。这两个方法在大部分情况下都是可以相互替换的,但是在使用了Spies对象(@Spy注解),而不是mock对象(@Mock注解)的情况下他们调用的结果是不相同的(目前我只知道这一种情况,可能还有别的情形下是不能相互替换的)。
    ● when(...) thenReturn(...)会调用真实的方法,如果你不想调用真实的方法而是想要mock的话,就不要使用这个方法。
    ● doReturn(...) when(...) 不会调用真实方法
    下面我写一个简单的单元测试来验证一下。
    1.被测试类

    public class Myclass {
        public String methodToBeTested(){
            return function();
        }
    
        public String function(){
            throw  new NullPointerException();
        }
    }

    2.单元测试

    @RunWith(MockitoJUnitRunner.class)
    public class MyclassTest {
        @Spy
        private Myclass myclass;
    
        @Test
        public void test(){
           // when(myclass.methodToBeTested()).thenReturn("when(...)thenReturn(...)");
            doReturn("doReturn(...)when(...)").when(myclass).methodToBeTested();
    
            String str = myclass.methodToBeTested();
            System.out.println(str);
        }
    }

    测试结果

    1.使用when(...).thenReturn(...),抛出了异常。

    2.doReturn(...).when(...),测试通过

  • 相关阅读:
    bzoj1202 狡猾的商人
    bzoj1059 矩阵游戏
    bzoj1003 物流运输
    bzoj1601 灌水
    2017-10-25模拟赛
    洛谷—— P1051 谁拿了最多奖学金
    BZOJ——1611: [Usaco2008 Feb]Meteor Shower流星雨
    2017-10-23学大伟业Day1
    BZOJ——1610: [Usaco2008 Feb]Line连线游戏
    Vijos 包裹快递(二分)
  • 原文地址:https://www.cnblogs.com/lanqi/p/7865163.html
Copyright © 2011-2022 走看看