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