How to mock method call and return value without running the method?

前端 未结 2 1996
攒了一身酷
攒了一身酷 2021-02-07 04:24

Consider the following method:

public boolean isACertainValue() {
        if(context.getValueA() != null && context.getValueA().toBoolean() == true) {
           


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-07 04:41

    When you are invoking

    Mockito.when(spy.isCertainValue()).thenReturn(true);
    

    the method isCertainValue() is getting called here. This is how Java works: to evaluate the argument of Mockito.when, the result of spy.isCertainValue() must be evaluated so the method must be called.

    If you don't want that to happen, you can use the following construct:

    Mockito.doReturn(true).when(spy).isCertainValue();
    

    This will have the same mocking effect but the method won't be called with this.

提交回复
热议问题