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

前端 未结 2 1995
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2021-02-07 04:47

    This code is correct:

    Mockito.when(contextMock.getType()).thenReturn(ContextType.certainType);
    

    But you are getting NullPointerException because you didn't define the Mocking value that should be defines, well I'm using Spring, in my context file when I define @Autowired bean I define it this way:

    <bean id="contextMock" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="com.example.myspringproject.bean.ContextMock" />
    </bean>
    
    0 讨论(0)
提交回复
热议问题