Interface ValidableAnswer


  • public interface ValidableAnswer
    Allow to validate this answer is correct for the given invocation.

    When tests use a shared answer implementation, it may happen the answer cannot be used with some methods. Implementing this interface indicate to Mockito it needs to verify the answer is compatible with the stubbed interaction.

    In the following example the answer is shared and work as expected...

    
     when(mock.someMethod(anyString())).then(doSomethingTricky());
    
     static Answer doSomethingTricky() {
         return new Answer() {
             Object answer(InvocationOnMock invocation) {
                 // tricky stuff
             }
         });
     }
     

    ...then later there's some refactoring or some new code that want to use the answer, however it is not compatible anymore. In this example the answer may throw an exception because the Answer cannot work with the return type or some parameter types.

    
     when(mock.someMethod(anyString(), anyInt())).then(doSomethingTricky()); // fail at answer execution time
     when(mock.incompatibleMethod(any())).then(doSomethingTricky()); // fail at answer execution time
     

    Instead of having an exception raised later at answer execution time, one can make this answer validable at stub time by implementing this contract.

    
     when(mock.incompatibleMethod(any())).then(doSomethingTricky()); // fail at answer stub time
    
     static Answer doSomethingTricky() {
         return new TrickyAnswer();
     }
    
     class Tricky Answer implements Answer, ValidableAnswer {
         public Object answer(InvocationOnMock invocation) {
             // tricky stuff
         }
    
         public void validateFor(InvocationOnMock invocation) {
             // perform validation for this interaction
         }
     }
     

    Since:
    2.3.8
    • Method Detail

      • validateFor

        void validateFor​(InvocationOnMock invocation)
        Validation of the answer at stub time for the given invocation.

        This method will be called by Mockito.

        The implementation must throw an MockitoException to indicate that this answer is not valid for the given invocation. If the validation succeed the implementation must simply return without throwing.

        Parameters:
        invocation - The stubbed invocation
        Since:
        2.3.8