Esempio n. 1
0
  @Nullable
  public InstanceFactory findInstanceFactory(@Nonnull Type mockedType) {
    InstanceFactory instanceFactory = mockedTypesAndInstances.get(mockedType);

    if (instanceFactory != null) {
      return instanceFactory;
    }

    Class<?> mockedClass = getClassType(mockedType);
    //noinspection ReuseOfLocalVariable
    instanceFactory = mockedTypesAndInstances.get(mockedClass);

    if (instanceFactory != null) {
      return instanceFactory;
    }

    boolean abstractType = mockedClass.isInterface() || isAbstract(mockedClass.getModifiers());

    for (Entry<Type, InstanceFactory> entry : mockedTypesAndInstances.entrySet()) {
      Type registeredMockedType = entry.getKey();
      Class<?> registeredMockedClass = getClassType(registeredMockedType);

      if (abstractType) {
        registeredMockedClass = getMockedClassOrInterfaceType(registeredMockedClass);
      }

      if (mockedClass.isAssignableFrom(registeredMockedClass)) {
        instanceFactory = entry.getValue();
        break;
      }
    }

    return instanceFactory;
  }
  /**
   * Sets up the mocks defined in the given mock class.
   *
   * <p>If the type {@linkplain MockClass#realClass referred to} by the mock class is actually an
   * interface, then a {@linkplain #newEmptyProxy(ClassLoader, Class) new empty proxy} is created.
   *
   * @param mockClassOrInstance the mock class itself (given by its {@code Class} literal), or an
   *     instance of the mock class
   * @return the new proxy instance created for the mocked interface, or {@code null} otherwise
   * @throws IllegalArgumentException if a given mock class fails to specify the corresponding real
   *     class using the {@code @MockClass(realClass = ...)} annotation; or if a mock class defines
   *     a mock method for which no corresponding real method or constructor exists in the real
   *     class; or if the real method matching a mock method is {@code abstract}
   * @see #setUpMock(Class, Object)
   * @see #setUpMocks(Object...)
   * @see <a
   *     href="http://code.google.com/p/jmockit/source/browse/trunk/main/test/mockit/MockAnnotationsTest.java#696">
   *     Example</a>
   */
  public static <T> T setUpMock(Object mockClassOrInstance) {
    Class<?> mockClass;
    Object mock;

    if (mockClassOrInstance instanceof Class<?>) {
      mockClass = (Class<?>) mockClassOrInstance;
      mock = null;
    } else {
      mockClass = mockClassOrInstance.getClass();
      mock = mockClassOrInstance;
    }

    MockClassSetup setup = new MockClassSetup(mock, mockClass);
    Class<?> realClass = setup.getRealClass();
    T proxy = null;

    if (realClass.isInterface()) {
      //noinspection unchecked
      proxy = (T) newEmptyProxy(mockClass.getClassLoader(), realClass);
      setup.setRealClass(proxy.getClass());
    }

    setup.redefineMethods();

    return proxy;
  }