scala - Complex custom Matcher -
i writing tests json output of api calls in api, written play on scala. in tests, pattern keeps appearing, , deduplicate it.
val response = sut.index()(fakerequest()) val expected = json.parse("""{ "channels":[] }""") status(response) must equalto(ok) contenttype(response) must besome.which(_ == "application/json") contentasjson(response) mustequal expected
my first approach this:
def assertsamejson(response: future[result], expected: jsvalue): unit = { status(response) must equalto(ok) contenttype(response) must besome.which(_ == "application/json") contentasjson(response) mustequal expected }
but not feel idiomatic @ all. seems adding xunit asserts in specs
i leading to
response must besamejson(expected)
the closest thing managed was
def besamejson(other:any) = be_==(other) ^^ ((t: future[result]) => contentasjson(t)) , be_==(ok) ^^ ((t: future[result]) => status(t))
but not check content-type, , feel it's hard read. there better way write matcher?
don't think there better way that. ^^ operator there purpose transform information before applying other matcher. and
can used combine more 2 matchers.
so thing try write bit cleaner:
def besamejson(data: string) = equalto(ok) ^^ {status(_: future[result])} , besome.which(_ == "application/json") ^^ {contenttype(_: future[result])} , be_==(other) ^^ {contentasjson(_: future[result])}
if need decompose responses more often, try more generically
object dummy extends matcher[any] { def apply[s <: any](s: expectable[s]) = { result(true, s.description + " ignored", s.description + " ignored", s) } } def beresponsewhere(json: matcher[jsvalue] = dummy, stat: matcher[int] = dummy, tpe: matcher[option[string]] = dummy) = stat ^^ {status(_: future[result])} , tpe ^^ {contenttype(_: future[result])} , json ^^ {contentasjson(_: future[result])} }
you should use nicer parameter names (i tried avoid conflict methods context example) , more complete on available attributes.
now should able write this:
response must beresponsewhere( json = equalto(expected), tpe = besome.which(_ == "application/json"), stat = equalto(ok) )
the dummymatcher allows leave parts out. did not try code not have complete setting. had guess types not clear code snippet.
Comments
Post a Comment