🚧 Add interactions helper for page maker
[Sone.git] / src / test / java / net / pterodactylus / sone / test / TestUtil.java
1 package net.pterodactylus.sone.test;
2
3 import java.lang.reflect.Constructor;
4 import java.lang.reflect.Field;
5 import java.lang.reflect.InvocationTargetException;
6 import java.lang.reflect.Method;
7 import java.lang.reflect.Modifier;
8
9 /**
10  * Utilities for testing.
11  */
12 public class TestUtil {
13
14         public static void setFinalField(Object object, String fieldName, Object value) {
15                 try {
16                         Field clientCoreField = object.getClass().getField(fieldName);
17                         clientCoreField.setAccessible(true);
18                         Field modifiersField = Field.class.getDeclaredField("modifiers");
19                         modifiersField.setAccessible(true);
20                         modifiersField.setInt(clientCoreField, clientCoreField.getModifiers() & ~Modifier.FINAL);
21                         clientCoreField.set(object, value);
22                 } catch (NoSuchFieldException | IllegalAccessException e) {
23                         throw new RuntimeException(e);
24                 }
25         }
26
27         public static <T> T getPrivateField(Object object, String fieldName) {
28                 try {
29                         Field field = object.getClass().getDeclaredField(fieldName);
30                         field.setAccessible(true);
31                         return (T) field.get(object);
32                 } catch (NoSuchFieldException | IllegalAccessException e) {
33                         throw new RuntimeException(e);
34                 }
35         }
36
37         public static <T> T callPrivateMethod(Object object, String methodName) {
38                 try {
39                         Method method = object.getClass().getDeclaredMethod(methodName, new Class[0]);
40                         method.setAccessible(true);
41                         return (T) method.invoke(object);
42                 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
43                         throw new RuntimeException(e);
44                 }
45         }
46
47         public static <T> T createObject(Class<T> clazz, Class[] parameterTypes, Object... arguments) {
48                 try {
49                         Constructor<T> constructor = clazz.getDeclaredConstructor(parameterTypes);
50                         constructor.setAccessible(true);
51                         return constructor.newInstance(arguments);
52                 } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
53                         throw new RuntimeException(e);
54                 }
55         }
56
57 }