View Javadoc
1   /*
2    * MIT License
3    * Copyright (c) 2006-2025 JMockit developers
4    * See LICENSE file for full license text.
5    */
6   package mockit;
7   
8   /**
9    * An empty interface to be used with the {@link Expectations#result} field or the
10   * <a href="Expectations.html#with(mockit.Delegate)">Invocations#with(Delegate)</a> method, allowing test code to define
11   * varying invocation results or argument matching rules, respectively.
12   * <p>
13   * When combined with the <code>result</code> field, a test will typically assign it with an anonymous class object
14   * implementing this interface and containing a <em>delegate method</em>:
15   *
16   * <pre>{@code
17   *    new Expectations() {{
18   *       mock.doSomething(anyInt, anyString);
19   *       result = new Delegate() {
20   *          String <strong>delegate</strong>(int i, String s) {
21   *             return i > 0 ? s : "";
22   *          }
23   *       };
24   *    }};
25   *
26   *    tested.exerciseCodeUnderTest();
27   * }</pre>
28   *
29   * The delegate class (either named or anonymous) must contain exactly one non-<code>private</code> instance method to
30   * be executed when the mocked method or mocked constructor is invoked; it can contain any number of
31   * <code>private</code> or <code>static</code> methods, though. The name of the delegate method can be anything. Its
32   * parameters, however, should be the same as the parameters of the corresponding mocked method/constructor, or at least
33   * be compatible with them. Optionally, the delegate method can have an extra parameter of type {@link Invocation},
34   * provided it appears as the first one. The delegate method is also allowed to have <em>no</em> parameters (without
35   * counting the optional <code>Invocation</code> parameter).
36   * <p>
37   * When used with the <code>result</code> field, the result of a delegate method execution can be any return value
38   * compatible with the recorded method's return type, or a thrown error/exception.
39   * <p>
40   * When used with the <code>with(Delegate)</code> method, the delegate method must return a <code>boolean</code>, being
41   * <code>true</code> for a successfully matched argument or <code>false</code> otherwise.
42   *
43   * @param <T>
44   *            the type of the argument to be matched, when used with the <code>with(Delegate)</code> method
45   *
46   * @see <a href="http://jmockit.github.io/tutorial/Mocking.html#delegates" target="tutorial">Tutorial</a>
47   */
48  public interface Delegate<T> {
49  }