Skip to content

Commit

Permalink
fixed files form Mockito #21
Browse files Browse the repository at this point in the history
  • Loading branch information
tdurieux committed Mar 7, 2017
1 parent e5fd500 commit f0ba112
Showing 1 changed file with 20 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,25 +14,41 @@ public <T> T newInstance(Class<T> cls) {
if (outerClassInstance == null) {
return noArgConstructor(cls);
}
return withOuterClass(cls);
return withParams(cls, outerClassInstance);
}

private <T> T withOuterClass(Class<T> cls) {
private static <T> T withParams(Class<T> cls, Object... params) {
try {
//this is kind of overengineered because we don't need to support more params
//however, I know we will be needing it :)
Constructor<T> c = cls.getDeclaredConstructor(outerClassInstance.getClass());
return c.newInstance(outerClassInstance);
for (Constructor<?> constructor : cls.getDeclaredConstructors()) {
Class<?>[] types = constructor.getParameterTypes();
if (paramsMatch(types, params)) {
return (T) constructor.newInstance(params);
}
}
} catch (Exception e) {
throw paramsException(cls, e);
}
throw paramsException(cls, null);
}

private static <T> InstantationException paramsException(Class<T> cls, Exception e) {
return new InstantationException("Unable to create mock instance of '"
+ cls.getSimpleName() + "'.\nPlease ensure that the outer instance has correct type and that the target class has parameter-less constructor.", e);
}

private static boolean paramsMatch(Class<?>[] types, Object[] params) {
if (params.length != types.length) {
return false;
}
for (int i = 0; i < params.length; i++) {
if (!types[i].isInstance(params[i])) {
return false;
}
}
return true;
}

private static <T> T noArgConstructor(Class<T> cls) {
try {
Expand Down

0 comments on commit f0ba112

Please sign in to comment.