hamkrest-moshi

Hamkrest matcher converting JSON data with Moshi

License

License

Categories

Categories

Moshi Data JSON
GroupId

GroupId

com.hypercubetools
ArtifactId

ArtifactId

hamkrest-moshi
Last Version

Last Version

0.1.0
Release Date

Release Date

Type

Type

pom.sha512
Description

Description

hamkrest-moshi
Hamkrest matcher converting JSON data with Moshi
Project URL

Project URL

https://github.com/plannigan/hamkrest-moshi
Source Code Management

Source Code Management

https://github.com/plannigan/hamkrest-moshi

Download hamkrest-moshi

Dependencies

runtime (3)

Group / Artifact Type Version
org.jetbrains.kotlin : kotlin-stdlib jar 1.3.72
com.natpryce : hamkrest jar 1.7.0.3
com.squareup.moshi : moshi jar 1.9.3

Project Modules

There are no modules declared in this project.

Kotlin CircleCI Download codecov

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 type
  • serializesTo() - 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)

Versions

Version
0.1.0