Last active
December 30, 2017 06:32
-
-
Save miguelortegarodriguez/7e488f7d2d3acf27d547530a79d97576 to your computer and use it in GitHub Desktop.
Scala test matcher to compare jsons
This file contains hidden or 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
import org.scalactic.Prettifier | |
import org.scalatest.matchers.{MatchResult, Matcher} | |
import org.scalatest.{FunSpec, Matchers} | |
import org.skyscreamer.jsonassert.{JSONCompare, JSONCompareMode} | |
trait JsonEqualityMatcher { | |
def equalsToJson(spread: String): Matcher[String] = { | |
new Matcher[String] { | |
def apply(left: String): MatchResult = { | |
val result = JSONCompare.compareJSON(left, spread, JSONCompareMode.STRICT) | |
MatchResult( | |
!result.failed(), | |
"json are not equals", | |
result.getMessage | |
) | |
} | |
override def toString: String = "jsonEqual (" + Prettifier.default(spread) + ")" | |
} | |
} | |
} | |
class JsonEqualityMatcherSpec extends FunSpec with Matchers with JsonEqualityMatcher { | |
describe("equalsToJson matcher") { | |
val jsonA = | |
"""{ | |
|"a": "a", | |
|"b": { | |
| "c": "123", "d": "abc" | |
|} | |
|}""".stripMargin | |
describe("for two json strings if they are structurally equals") { | |
val jsonB = | |
"""{"a": "a", "b": { | |
|"c": "123", | |
|"d": "abc"} | |
|}""".stripMargin | |
it("should return a positive a matching") { | |
jsonA should equalsToJson(jsonB) | |
} | |
} | |
describe("for two json strings that are not structurally equals") { | |
val jsonC = | |
"""{"b": "4444", "z": { | |
|"j": "123", | |
|"d": "abc"} | |
|}""".stripMargin | |
it("should return a positive a matching") { | |
jsonA should not(equalsToJson(jsonC)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment