hamkrest-moshi
Hamkrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively.
hamkrest-moshi
provides matchers that can be used to assert Moshi can serialize and deserialize JSON content.
Usage
hamkrest-moshi
exposes two function:
deserializesTo()
- Verify that a JSON string can be converted to a specific typeserializesTo()
- Verify that a value can be converted to a JSON string
Examples:
hamkrest-moshi
works best when using Moshi's code generation functionality.
@JsonClass(generateAdapter = true)
data class Bar(val key: String, val count: Int)
val someBar = Bar(key = "bar-123", count = 50)
// Verify Moshi can convert to and from a specific type
assertThat(someBar, serializesTo<Bar>())
assertThat("""{"key":"bar-123","count":50}""", deserializesTo<Bar>())
// Verify the converted value is equal to a specific value
assertThat(someBar, serializesTo<Bar>("""{"key":"bar-123","count":50}"""))
assertThat("""{"key":"bar-123","count":50}""", deserializesTo(someBar))
// Use a custom matcher on the converted value
assertThat(someBar, serializesTo<Bar>(containsSubstring("bar-123")))
assertThat("""{"key":"bar-123","count":50}""", deserializesTo(has(Bar::key, !isEmptyString)))
When using Moshi's code generation functionality, a Moshi
instance that was configured to use reflection must be passed in.
data class Foo(val id: Int, val name: String)
val someFoo = Foo(42, "Fooius")
val reflectionMoshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
assertThat("""{"id":42,"name":"Fooius"}""", deserializesTo(someFoo), moshi = reflectionMoshi)