1 /* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5 package org.mockito.stubbing; 6 7 import org.mockito.invocation.InvocationOnMock; 8 9 /** 10 * Allow to validate this answer is correct for the given invocation. 11 * 12 * <p> 13 * When tests use a shared answer implementation, it may happen the answer cannot be used 14 * with some methods. Implementing this interface indicate to Mockito it needs to verify the answer is compatible 15 * with the stubbed interaction. 16 * </p> 17 * 18 * <p> 19 * In the following example the answer is shared and work as expected... 20 * 21 * <pre class="code"><code class="java"> 22 * when(mock.someMethod(anyString())).then(doSomethingTricky()); 23 * 24 * static Answer doSomethingTricky() { 25 * return new Answer() { 26 * Object answer(InvocationOnMock invocation) { 27 * // tricky stuff 28 * } 29 * }); 30 * } 31 * </code></pre> 32 * </p> 33 * 34 * <p> 35 * ...then later there's some refactoring or some new code that want to use the answer, 36 * however it is not compatible anymore. In this example the answer may throw an exception because 37 * the Answer cannot work with the return type or some parameter types. 38 * 39 * <pre class="code"><code class="java"> 40 * when(mock.someMethod(anyString(), anyInt())).then(doSomethingTricky()); // fail at answer execution time 41 * when(mock.incompatibleMethod(any())).then(doSomethingTricky()); // fail at answer execution time 42 * </code></pre> 43 * </p> 44 * 45 * <p> 46 * Instead of having an exception raised later at answer <em>execution time</em>, one can make this answer 47 * validable at <em>stub time</em> by implementing this contract. 48 * 49 * <pre class="code"><code class="java"> 50 * when(mock.incompatibleMethod(any())).then(doSomethingTricky()); // fail at answer stub time 51 * 52 * static Answer doSomethingTricky() { 53 * return new TrickyAnswer(); 54 * } 55 * 56 * class Tricky Answer implements Answer, ValidableAnswer { 57 * public Object answer(InvocationOnMock invocation) { 58 * // tricky stuff 59 * } 60 * 61 * public void validateFor(InvocationOnMock invocation) { 62 * // perform validation for this interaction 63 * } 64 * } 65 * </code></pre> 66 * </p> 67 * 68 * @since 2.3.8 69 */ 70 public interface ValidableAnswer { 71 72 /** 73 * Validation of the answer at <em>stub time</em> for the given invocation. 74 * 75 * <p> 76 * This method will be called by Mockito. 77 * </p> 78 * 79 * <p> 80 * The implementation must throw an MockitoException to indicate that this answer is not valid for 81 * the given invocation. If the validation succeed the implementation must simply return without throwing. 82 * </p> 83 * 84 * @param invocation The stubbed invocation 85 * 86 * @since 2.3.8 87 */ validateFor(InvocationOnMock invocation)88 void validateFor(InvocationOnMock invocation); 89 } 90