22
22
import difflib .Patch ;
23
23
24
24
public class SnapshotMatcher <T > extends TypeSafeMatcher <T > {
25
+ /**
26
+ * Factory method to instantiate a snapshot matcher with the given type
27
+ *
28
+ * @param <T> Type of object to snapshot
29
+ * @return The snapshot matcher instance
30
+ */
25
31
@ Factory
26
32
public static <T > SnapshotMatcher <T > matchesSnapshot () {
27
33
return new SnapshotMatcher <>();
28
34
}
29
35
36
+ /**
37
+ * Private constructor, use factory method {@link SnapshotMatcher#matchesSnapshot()} create a new matcher
38
+ */
30
39
private SnapshotMatcher () {
31
40
}
32
41
@@ -46,6 +55,12 @@ public boolean matchesSafely(T o) {
46
55
}
47
56
}
48
57
58
+ /**
59
+ * Perform serialization of o and save result to snapshotPath
60
+ *
61
+ * @param o Object to serialize
62
+ * @param snapshotPath Path to file to create
63
+ */
49
64
private void createSnapshot (T o , Path snapshotPath ) {
50
65
try {
51
66
Files .createDirectories (snapshotPath .getParent ());
@@ -59,6 +74,13 @@ private void createSnapshot(T o, Path snapshotPath) {
59
74
}
60
75
}
61
76
77
+ /**
78
+ * Compares snapshot at the given path with the given object
79
+ *
80
+ * @param o Actual object to serialize then compare
81
+ * @param snapshotPath Path to the corresponding snapshot file
82
+ * @return true if snapshot matches the actual, false otherwise
83
+ */
62
84
private boolean compareSnapshot (T o , Path snapshotPath ) {
63
85
try (BufferedReader reader = Files .newBufferedReader (snapshotPath , Charset .forName ("UTF-8" ))) {
64
86
List <String > actual = asList (objectMapper .writeValueAsString (o ).split (System .lineSeparator ()));
@@ -96,6 +118,11 @@ public void describeTo(Description description) {
96
118
description .appendText ("Object should match snapshot at " + getPath ().toString ());
97
119
}
98
120
121
+ /**
122
+ * Find out path of the snapshot using caller name and class
123
+ *
124
+ * @return Path to the snapshot file
125
+ */
99
126
private Path getPath () {
100
127
StackTraceElement caller = getCaller ();
101
128
@@ -105,6 +132,11 @@ private Path getPath() {
105
132
return Paths .get (String .format ("src/test/resources/snapshots/%s/%s.json" , callerClassName , callerMethodName ));
106
133
}
107
134
135
+ /**
136
+ * Find out caller StackTraceElement, ie. the test method which instantiated the matcher
137
+ *
138
+ * @return StackTraceElement of the test method
139
+ */
108
140
private StackTraceElement getCaller () {
109
141
final StackTraceElement [] stackTraceElements = Thread .currentThread ().getStackTrace ();
110
142
0 commit comments