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