diff --git a/Home.md b/Home.md index 5de94c4..1f9e976 100644 --- a/Home.md +++ b/Home.md @@ -53,4 +53,59 @@ Toggle terminal with `ctrl+tilda` and type ./gradlew test ``` -## Testing the Data Contract +## Testing the CashCard Data Contract + +```java +import org.springframework.boot.test.json.JacksonTester; +import org.springframework.beans.factory.annotation.Autowired; + +@JsonTest +public class CashCardJsonTest { + + @Autowired + private JacksonTester json; +``` + +Marking CashCardJsonTest with `@JsonTest` annotation makes it a test class which uses the Jackson framework (which is included as part of Spring). This provides extensive JSON testing and parsing support. It also establishes all the related behavior to test JSON objects. + +### @Autowired + +`@Autowired` is an annotation that directs Spring to create an object of the requested type. `JacksonTester` is a convenience wrapper to the Jackson JSON parsing library. It handles serialization and deserialization of JSON objects. + +To create a CashCard class and the constructor that’s used in the cashCardSerializationTest() test, create the file `src/main/java/example/cashcard/CashCard.java` with the following contents (notice that this file is under in the src/main directory, not the src/test directory): + +```java +package example.cashcard; + +public record CashCard(Long id, Double amount) { +} +``` + +### The contract file + +`src/test/resources/example/cashcard/expected.json` + +```json +{ + "id": 99, + "amount": 123.45 +} +``` + +### The test + +```java +@Test + public void cashCardSerializationTest() throws IOException { + CashCard cashCard = new CashCard(99L, 123.45); + assertThat(json.write(cashCard)).isStrictlyEqualToJson("expected.json"); + assertThat(json.write(cashCard)).hasJsonPathNumberValue("@.id"); + assertThat(json.write(cashCard)).extractingJsonPathNumberValue("@.id") + .isEqualTo(99); + assertThat(json.write(cashCard)).hasJsonPathNumberValue("@.amount"); + assertThat(json.write(cashCard)).extractingJsonPathNumberValue("@.amount") + .isEqualTo(123.45); + } +``` + +