diff --git a/README.md b/README.md index ad864af..573ab34 100644 --- a/README.md +++ b/README.md @@ -93,5 +93,21 @@ public class PlanetConverterTest { } ``` +## Activate snapshot writing +Snapshots must be written at the same time as the tests. +It is necessary to avoid writing them in CI environments. + +To activate snapshot writing, pass the VM option `-Dtest.snapshots.write`. + +### With Maven +```bash +mvn -Dtest.snapshots.write test +``` + +### With Intellij +Set VM option inside test run configuration. + +![](./writesnapshot-intellij.png) + ## Limitations - Only one snapshot assertion per test method diff --git a/snapshot-matcher/src/main/java/com/zenika/snapshotmatcher/SnapshotMatcher.java b/snapshot-matcher/src/main/java/com/zenika/snapshotmatcher/SnapshotMatcher.java index 0bebe61..d5da91f 100644 --- a/snapshot-matcher/src/main/java/com/zenika/snapshotmatcher/SnapshotMatcher.java +++ b/snapshot-matcher/src/main/java/com/zenika/snapshotmatcher/SnapshotMatcher.java @@ -22,6 +22,9 @@ import difflib.Patch; public class SnapshotMatcher extends TypeSafeMatcher { + + private static final String SNAPSHOT_WRITE_VARIABLE = "test.snapshots.write"; + /** * Factory method to instantiate a snapshot matcher with the given type * @@ -48,11 +51,14 @@ public boolean matchesSafely(T o) { if (Files.exists(snapshotPath)) { // File exists => Compare snapshot file to given object return compareSnapshot(o, snapshotPath); - } else { + } else if (isWriteSnapshotActivated()) { // File doesn't exist => Create snapshot file and return true createSnapshot(o, snapshotPath); return true; } + System.out.println("Snapshot writing is not activated in this environment."); + System.out.println("Activate snapshot writing by using -D" + SNAPSHOT_WRITE_VARIABLE); + return false; } /** @@ -153,4 +159,7 @@ private StackTraceElement getCaller() { .orElse(null); } + private boolean isWriteSnapshotActivated() { + return System.getProperty(SNAPSHOT_WRITE_VARIABLE) != null; + } } diff --git a/writesnapshot-intellij.png b/writesnapshot-intellij.png new file mode 100644 index 0000000..3242ff3 Binary files /dev/null and b/writesnapshot-intellij.png differ