Mockito UnfinishedStubbingException

前端 未结 4 1305
离开以前
离开以前 2020-12-09 08:49

I am new to Mockito, I have tried looking into this Exception but I haven´t found a concrete answer. It happens in my code when I use two mocks together, meaning that I give

4条回答
  •  失恋的感觉
    2020-12-09 09:45

    From what I read on "Issue 53" of mockito (https://code.google.com/p/mockito/issues/detail?id=53) , my code was experiencing a problem due to the validation framework involved in Mockito. Precisely the following code was causing the exception per se.

    private ConstantNode getConstantNode(NumericalValue value){
        ConstantNode node = Mockito.mock(ConstantNode.class);
        Mockito.when(node.evaluate()).thenReturn(value);
        Mockito.when(node.toString()).thenReturn(value.toString());
        return node;
    }
    

    If you remember from my code, the parameter value is ALSO A MOCK, so that when value.toString() is called on the thenReturn(), I believe (and someone please correct me if I am wrong) that the validation framework is triggered and makes sure that every "when" has had its thenReturn() called/validated/etc. So that if this happenes, the Mockito.when(node.toString()).thenReturn(value.toString() will not be validated because it hasn´t returned from the valute.toString(), which started the whole "validate everything" chain.

    How I fixed it:

    private ConstantNode getConstantNode(NumericalValue value){
        ConstantNode node = Mockito.mock(ConstantNode.class);
        Mockito.when(node.evaluate()).thenReturn(value);
    
        String numberToString = value.toString();
    
        Mockito.when(node.toString()).thenReturn(numberToString);
        return node;
    }
    

    This way, it can be validated. I find this a complete code smell because I will literally have to leave a comment that explains why I am using a seemingly useless intermediate variable in the code.

    Thanks for the help.

提交回复
热议问题