From 965f752f826fe3fa0f8f62b10ff8f37856b27c61 Mon Sep 17 00:00:00 2001 From: Martin Welgemoed Date: Mon, 11 Sep 2023 10:01:58 +0200 Subject: [PATCH] Added test for optional list --- .../io/sphere/json/OptionReaderSpec.scala | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/json/json-derivation/src/test/scala/io/sphere/json/OptionReaderSpec.scala b/json/json-derivation/src/test/scala/io/sphere/json/OptionReaderSpec.scala index 63a476ba..affb805e 100644 --- a/json/json-derivation/src/test/scala/io/sphere/json/OptionReaderSpec.scala +++ b/json/json-derivation/src/test/scala/io/sphere/json/OptionReaderSpec.scala @@ -1,7 +1,7 @@ package io.sphere.json import io.sphere.json.generic._ -import org.json4s.{JLong, JNothing, JObject, JString} +import org.json4s.{JArray, JLong, JNothing, JObject, JString} import org.scalatest.OptionValues import org.scalatest.matchers.must.Matchers import org.scalatest.wordspec.AnyWordSpec @@ -24,6 +24,11 @@ object OptionReaderSpec { object MapClass { implicit val json: JSON[MapClass] = jsonProduct(apply _) } + + case class ListClass(id: Long, list: Option[List[String]]) + object ListClass { + implicit val json: JSON[ListClass] = jsonProduct(apply _) + } } class OptionReaderSpec extends AnyWordSpec with Matchers with OptionValues { @@ -84,6 +89,24 @@ class OptionReaderSpec extends AnyWordSpec with Matchers with OptionValues { JObject("id" -> JLong(1L), "map" -> JObject("a" -> JString("b"))) } + "handle optional list" in { + getFromJValue[ListClass]( + JObject("id" -> JLong(1L), "list" -> JArray(List(JString("hi"))))) mustEqual + ListClass(1L, Some(List("hi"))) + getFromJValue[ListClass](JObject("id" -> JLong(1L), "list" -> JArray(List.empty))) mustEqual + ListClass(1L, Some(List())) + getFromJValue[ListClass](JObject("id" -> JLong(1L))) mustEqual + ListClass(1L, None) + + toJValue(ListClass(1L, Some(List("hi")))) mustEqual JObject( + "id" -> JLong(1L), + "list" -> JArray(List(JString("hi")))) + toJValue(ListClass(1L, Some(List.empty))) mustEqual JObject( + "id" -> JLong(1L), + "list" -> JArray(List.empty)) + toJValue(ListClass(1L, None)) mustEqual JObject("id" -> JLong(1L), "list" -> JNothing) + } + "handle absence of all fields mixed with ignored fields" in { val json = """{ "value3": "a" }""" val result = getFromJSON[Option[SimpleClass]](json)