Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test for constructing Writes with case class #1040

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,19 +246,28 @@ import play.api.libs.functional.syntax._
implicit val locationWrites: Writes[Location] = (
(JsPath \ "lat").write[Double] and
(JsPath \ "long").write[Double]
)(unlift(Location.unapply))
)(location => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Snippets should show use cases for both versions

val Location(lat, long) = location
(lat, long)
})

implicit val residentWrites: Writes[Resident] = (
(JsPath \ "name").write[String] and
(JsPath \ "age").write[Int] and
(JsPath \ "role").writeNullable[String]
)(unlift(Resident.unapply))
)(resident => {
val Resident(name, age, role) = resident
(name, age, role)
})

implicit val placeWrites: Writes[Place] = (
(JsPath \ "name").write[String] and
(JsPath \ "location").write[Location] and
(JsPath \ "residents").write[Seq[Resident]]
)(unlift(Place.unapply))
)(place => {
val Place(name, location, residents) = place
(name, location, residents)
})


val place = Place(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,31 @@ final class WritesSharedSpec extends AnyWordSpec with Matchers {
success[JsValue, Writes](JsString("foo"))
}

"Constructing Writes" should {
"support case class" in {
import play.api.libs.functional.syntax._

implicit val locationReads: Reads[Location] = (
(JsPath \ "lat").read[Double] and
(JsPath \ "long").read[Double]
)(Location.apply _)

implicit val locationWrites: Writes[Location] = (
(JsPath \ "lat").write[Double] and
(JsPath \ "long").write[Double]
)(location => {
val Location(lat, long) = location
(lat, long)
})

val location = Location(1.1, 2.2)

val serialized = Json.stringify(Json.toJson(location))
serialized.mustEqual("""{"lat":1.1,"long":2.2}""")
Json.fromJson[Location](Json.parse(serialized)).mustEqual(JsSuccess(location))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not required to test Writes

}
}

// ---

case class Location(lat: Double, long: Double)
Expand Down
Loading