Last active
January 14, 2021 20:57
-
-
Save frankwis/62bb73c8791e8911bd6c441fbc255e8d to your computer and use it in GitHub Desktop.
Groovy type coercion examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// for a simple Java POJO | |
def patch = ["add","path", 42] as Patch // explicit coercion | |
Patch patch = ["add","path", 42] // implicit coercion | |
def patch = new Patch("add","path", 42) // default invocation | |
// mocking via coercion | |
def service = [getValue: { UUID id -> 42 }] as CounterService // map coercion | |
def service = { UUID id -> 42 } as CounterService // closure coercion | |
assert 42 == service.getValue(UUID.randomUUID()) | |
// GroovyBean with auto-generated map constructor (plus getter and setter) | |
// equals() and hashcode() generated via @EqualsAndHashCode annotation | |
@EqualsAndHashCode | |
class Patch { | |
String op; | |
String path; | |
long value; | |
} | |
def patch = [op: 'add', path: 'path', value: 42] as Patch // explicit | |
Patch patch = [op: 'add', path: 'path', value: 42] // implicit | |
// facilitating native map syntax for REST payloads | |
def patch = [ | |
"op" : "add", | |
"path" : "path", | |
"value": 42 | |
] | |
RestAssured | |
.given() | |
.contentType("application/json-patch+json") | |
.body(patch) | |
.patch(someUrl) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class CounterService { | |
... | |
public long getValue(UUID id) { | |
return counters.get(id); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Patch { | |
public final String op; | |
public final String path; | |
public final long value; | |
@JsonCreator | |
public Patch(@JsonProperty(value = "op", required = true) String op, | |
@JsonProperty(value = "path", required = true) String path, | |
@JsonProperty(value = "value", required = true) long value) { | |
this.op = op; | |
this.path = path; | |
this.value = value; | |
verifyOperation(); | |
} | |
private void verifyOperation() { | |
if (!"ADD".equalsIgnoreCase(op)) { | |
throw new InvalidPatchOperationException("Currently only ADD is supported for PATCH."); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment