generated from java-cli-apps/basic-java-23-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestHelper.java
More file actions
56 lines (49 loc) · 2.16 KB
/
TestHelper.java
File metadata and controls
56 lines (49 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import module java.base;
import static java.util.stream.Collectors.joining;
class TestHelper {
static void runTests(Class<?>... classes) {
for (Class<?> clazz : classes) {
runTests(getInstance(clazz));
}
}
static String runApplication(String name, String... args) {
try {
var command = new ArrayList<String>();
command.add(name);
command.addAll(List.of(args));
var process = new ProcessBuilder(command).start();
try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String output = reader.lines().collect(joining("\n"));
process.waitFor();
return output;
}
} catch (Exception exception) {
throw new RuntimeException("Application has failed to start", exception);
}
}
private static void runTests(Object instance) {
Arrays.stream(instance.getClass().getDeclaredMethods())
.filter(method -> method.getName().toLowerCase().contains("test"))
.forEach(method -> runTest(instance, method));
}
private static void runTest(Object instance, Method method) {
var testName = method.getName();
try {
method.invoke(instance);
IO.println("✅ Test %s is successful".formatted(testName));
} catch (InvocationTargetException targetException) {
IO.println("❌ Test %s has failed".formatted(testName));
targetException.getCause().printStackTrace();
} catch (IllegalAccessException accessException) {
throw new RuntimeException("Failed to run test: %s".formatted(testName), accessException);
}
}
private static Object getInstance(Class<?> clazz) {
try {
return clazz.getDeclaredConstructor(new Class[]{}).newInstance();
} catch (InstantiationException | IllegalAccessException | InvocationTargetException |
NoSuchMethodException exception) {
throw new RuntimeException("Failed to instantiate Test class: %s".formatted(clazz.getName()), exception);
}
}
}