public IMockBuilder<T> withArgs(Object... initArgs) { if (constructor == null) { throw new IllegalStateException( "Trying to define constructor arguments without first setting their type."); } if (constructorArgs != null) { throw new IllegalStateException("Trying to define the constructor arguments more than once."); } constructorArgs = new ConstructorArgs(constructor, initArgs); return this; }
public IMockBuilder<T> withConstructor(ConstructorArgs constructorArgs) { checkConstructorNotInitialized(); this.constructor = constructorArgs.getConstructor(); this.constructorArgs = constructorArgs; return this; }
/** * @param constructor * Constructor to be called when creating the mock * @param initArgs * Arguments passed to the constructor */ public ConstructorArgs(Constructor<?> constructor, Object... initArgs) { this.constructor = constructor; this.initArgs = initArgs; validateArgs(); }
try { cstr = mockClass.getDeclaredConstructor(args.getConstructor().getParameterTypes()); } catch (NoSuchMethodException e) { cstr.setAccessible(true); // So we can call a protected mock = (Factory) cstr.newInstance(args.getInitArgs()); } catch (InstantiationException | IllegalAccessException e) {
throw throwException(paramType, arg); throw throwException(paramType, arg); throw throwException(paramType, arg);
public <T> T createProxy(Class<T> toMock, InvocationHandler handler, Method[] mockedMethods, ConstructorArgs constructorArgs) { MockHandler interceptor = new MockHandler(handler, mockedMethods); try { ProxyBuilder<T> builder = ProxyBuilder.forClass(toMock) .handler(interceptor); if (constructorArgs != null) { builder.constructorArgTypes(constructorArgs.getConstructor().getParameterTypes()) .constructorArgValues(constructorArgs.getInitArgs()); } else { try { DefaultClassInstantiator instantiator = new DefaultClassInstantiator(); Constructor<?> constructor = instantiator.getConstructorToUse(toMock); Object[] params = instantiator.getArgsForTypes(constructor.getParameterTypes()); builder.constructorArgTypes(constructor.getParameterTypes()) .constructorArgValues(params); } catch (InstantiationException e) { throw new RuntimeException("Fail to instantiate mock for " + toMock); } } return builder.build(); } catch (IOException e) { throw new RuntimeException("Failed to mock " + toMock, e); } }
public IMockBuilder<T> withConstructor() { checkConstructorNotInitialized(); try { constructor = ReflectionUtils.getConstructor(toMock); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("No empty constructor can be found", e); } constructorArgs = new ConstructorArgs(constructor); return this; }
public IMockBuilder<T> withConstructor(Object... initArgs) { checkConstructorNotInitialized(); try { constructor = ReflectionUtils.getConstructor(toMock, initArgs); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("No constructor matching arguments can be found", e); } constructorArgs = new ConstructorArgs(constructor, initArgs); return this; }