Debian Codegraph @

jmock-junit5/src/test/java/org/jmock/junit5/extensions/ExpectationExtension.java

raw
1 package org.jmock.junit5.extensions;
2
3 import java.lang.annotation.Annotation;
4 import java.util.Timer;
5 import java.util.TimerTask;
6
7 import org.junit.jupiter.api.Assertions;
8 import org.junit.jupiter.api.extension.AfterEachCallback;
9 import org.junit.jupiter.api.extension.BeforeEachCallback;
10 import org.junit.jupiter.api.extension.Extension;
11 import org.junit.jupiter.api.extension.ExtensionContext;
12 import org.junit.jupiter.api.extension.TestExecutionExceptionHandler;
13
14 import com.google.auto.service.AutoService;
15
16 @AutoService(Extension.class)
17 public class ExpectationExtension implements TestExecutionExceptionHandler, BeforeEachCallback, AfterEachCallback {
18
19 private Throwable thrown = null;
20 private Timer timer = null;
21
22 @Override
23 public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable {
24 if (isAnnotated(context, ExpectationThrows.class)) {
25 if (!readExpectedFromAnnotations(context).isAssignableFrom(throwable.getClass())) {
26 throw throwable;
27 }
28 thrown = throwable;
29 }
30 }
31
32 @Override
33 public void beforeEach(ExtensionContext context) throws Exception {
34 if (isAnnotated(context, ExpectationTimeout.class)) {
35 timer = new Timer(true);
36 timer.schedule(new TimerTask() {
37 @Override
38 public void run() {
39 Assertions.fail("Timed out");
40 }
41 }, readTimoutFromAnnotations(context));
42 }
43 }
44
45 @Override
46 public void afterEach(ExtensionContext context) throws Exception {
47 if (isAnnotated(context, ExpectationTimeout.class)) {
48 timer.cancel();
49 timer = null;
50 }
51
52 if (isAnnotated(context, ExpectationThrows.class)) {
53 Class<? extends Throwable> expected = readExpectedFromAnnotations(context);
54 if (thrown == null || !expected.isAssignableFrom(thrown.getClass())) {
55 Assertions.fail("Was expecting the throwable:" + expected.getName());
56 }
57 }
58 }
59
60 private boolean isAnnotated(ExtensionContext context, Class<? extends Annotation> annotation) {
61 return context.getRequiredTestMethod().isAnnotationPresent(annotation);
62 }
63
64 private Class<? extends Throwable> readExpectedFromAnnotations(ExtensionContext context) {
65 ExpectationThrows annotation = context.getRequiredTestMethod().getAnnotation(ExpectationThrows.class);
66 return annotation.expected();
67 }
68
69 private long readTimoutFromAnnotations(ExtensionContext context) {
70 ExpectationTimeout annotation = context.getRequiredTestMethod().getAnnotation(ExpectationTimeout.class);
71 return annotation.timeout();
72 }
73 }