From 9a0ad2b059552a6c6a7608694f32cf0c446ab1e2 Mon Sep 17 00:00:00 2001 From: Stephan Schroevers Date: Sat, 23 Dec 2023 22:07:59 +0100 Subject: [PATCH] Add `JsonTest` --- .../errorprone/documentation/JsonTest.java | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 documentation-support/src/test/java/tech/picnic/errorprone/documentation/JsonTest.java diff --git a/documentation-support/src/test/java/tech/picnic/errorprone/documentation/JsonTest.java b/documentation-support/src/test/java/tech/picnic/errorprone/documentation/JsonTest.java new file mode 100644 index 0000000000..6fd9689dd4 --- /dev/null +++ b/documentation-support/src/test/java/tech/picnic/errorprone/documentation/JsonTest.java @@ -0,0 +1,62 @@ +package tech.picnic.errorprone.documentation; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.google.auto.value.AutoValue; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +final class JsonTest { + private static final TestObject TEST_OBJECT = new AutoValue_JsonTest_TestObject("foo", 42); + private static final String TEST_JSON = "{\"string\":\"foo\",\"number\":42}"; + + @Test + void write(@TempDir Path directory) { + Path file = directory.resolve("test.json"); + + Json.write(file, TEST_OBJECT); + + assertThat(file).content(UTF_8).isEqualTo(TEST_JSON); + } + + @Test + void writeFailure(@TempDir Path directory) { + assertThatThrownBy(() -> Json.write(directory, TEST_OBJECT)) + .isInstanceOf(UncheckedIOException.class) + .hasMessageContaining("Failure writing to '%s'", directory) + .hasCauseInstanceOf(FileNotFoundException.class); + } + + @Test + void read(@TempDir Path directory) throws IOException { + Path file = directory.resolve("test.json"); + + Files.writeString(file, TEST_JSON, UTF_8); + + assertThat(Json.read(file, TestObject.class)).isEqualTo(TEST_OBJECT); + } + + @Test + void readFailure(@TempDir Path directory) { + assertThatThrownBy(() -> Json.read(directory, TestObject.class)) + .isInstanceOf(UncheckedIOException.class) + .hasMessageContaining("Failure reading from '%s'", directory) + .hasCauseInstanceOf(FileNotFoundException.class); + } + + @AutoValue + @JsonDeserialize(as = AutoValue_JsonTest_TestObject.class) + abstract static class TestObject { + abstract String string(); + + abstract int number(); + } +}