Пример #1
0
  @Override
  @SuppressWarnings("unchecked")
  public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
    Class<T> typeToMock = settings.getTypeToMock();
    @SuppressWarnings("rawtypes")
    Set<Class> interfacesSet = settings.getExtraInterfaces();
    Class<?>[] extraInterfaces = interfacesSet.toArray(new Class[interfacesSet.size()]);
    InvocationHandler invocationHandler = new InvocationHandlerAdapter(handler);

    if (typeToMock.isInterface()) {
      // support interfaces via java.lang.reflect.Proxy
      @SuppressWarnings("rawtypes")
      Class[] classesToMock = new Class[extraInterfaces.length + 1];
      classesToMock[0] = typeToMock;
      System.arraycopy(extraInterfaces, 0, classesToMock, 1, extraInterfaces.length);
      ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
      // newProxyInstance returns the type of typeToMock
      T mock = (T) Proxy.newProxyInstance(contextClassLoader, classesToMock, invocationHandler);
      return mock;

    } else {
      try {
        Class<? extends T> proxyClass = getProxyClass(typeToMock, extraInterfaces);
        T mock = proxyClass.newInstance();
        ((ClassProxy) mock).setHandler(invocationHandler);
        return mock;
      } catch (RuntimeException e) {
        throw e;
      } catch (Exception e) {
        throw new MockitoException("Failed to mock " + typeToMock, e);
      }
    }
  }
 public <T> T createMock(MockCreationSettings<T> settings, MockHandler handler) {
   InternalMockHandler mockitoHandler = cast(handler);
   return ClassImposterizer.INSTANCE.imposterise(
       new MethodInterceptorForGroovyFilter(mockitoHandler, settings),
       settings.getTypeToMock(),
       settings.getExtraInterfaces());
 }