|
| 1 | +package com.baeldung.json |
| 2 | + |
| 3 | +import spock.lang.Specification |
| 4 | + |
| 5 | +import java.text.SimpleDateFormat |
| 6 | + |
| 7 | +class JsonParserTest extends Specification { |
| 8 | + |
| 9 | + JsonParser jsonParser |
| 10 | + |
| 11 | + void setup () { |
| 12 | + jsonParser = new JsonParser() |
| 13 | + } |
| 14 | + |
| 15 | + def 'Should parse to Account given Json String' () { |
| 16 | + given: |
| 17 | + def json = '{"id":"1234","value":15.6}' |
| 18 | + when: |
| 19 | + def account = jsonParser.toObject(json) |
| 20 | + then: |
| 21 | + account |
| 22 | + account instanceof Account |
| 23 | + account.id == '1234' |
| 24 | + account.value == 15.6 |
| 25 | + } |
| 26 | + |
| 27 | + def 'Should parse to Account given Json String with date property' () { |
| 28 | + given: |
| 29 | + def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}' |
| 30 | + when: |
| 31 | + def account = jsonParser.toObjectWithIndexOverlay(json) |
| 32 | + then: |
| 33 | + account |
| 34 | + account instanceof Account |
| 35 | + account.id == '1234' |
| 36 | + account.value == 15.6 |
| 37 | + println account.createdAt |
| 38 | + account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01') |
| 39 | + } |
| 40 | + |
| 41 | + def 'Should parse to Json given an Account object' () { |
| 42 | + given: |
| 43 | + Account account = new Account( |
| 44 | + id: '123', |
| 45 | + value: 15.6, |
| 46 | + createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018') |
| 47 | + ) |
| 48 | + when: |
| 49 | + def json = jsonParser.toJson(account) |
| 50 | + then: |
| 51 | + json |
| 52 | + json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}' |
| 53 | + } |
| 54 | + |
| 55 | + def 'Should parse to Json given an Account object, a date format and fields to exclude' () { |
| 56 | + given: |
| 57 | + Account account = new Account( |
| 58 | + id: '123', |
| 59 | + value: 15.6, |
| 60 | + createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018') |
| 61 | + ) |
| 62 | + when: |
| 63 | + def json = jsonParser.toJson(account, 'MM/dd/yyyy', 'value') |
| 64 | + then: |
| 65 | + json |
| 66 | + json == '{"createdAt":"01/01/2018","id":"123"}' |
| 67 | + } |
| 68 | + |
| 69 | + def 'Should prettify given a json string' () { |
| 70 | + given: |
| 71 | + String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}' |
| 72 | + when: |
| 73 | + def jsonPretty = jsonParser.prettyfy(json) |
| 74 | + then: |
| 75 | + jsonPretty |
| 76 | + jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}' |
| 77 | + } |
| 78 | + |
| 79 | + |
| 80 | +} |
0 commit comments