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(...),测试通过

原文地址:https://www.cnblogs.com/lanqi/p/7865163.html