Update Home
parent
8a8ce2bfb5
commit
7ea1a78b5b
57
Home.md
57
Home.md
@ -53,4 +53,59 @@ Toggle terminal with `ctrl+tilda` and type
|
|||||||
./gradlew test
|
./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<CashCard> 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);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user