Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit test a controller in Play/Scala

I'm having trouble when trying to test a controller that sends a POST request to the API. I've tried different ways of testing it but I keep on getting the same "400" response. I believe the format of the json val is correct because I've tested it using Swagger and it works fine. Can anybody help me to understand what I'm missing here. Many thanks.

val json: JsValue = Json.parse("""[{"id":"1","address":"my address"}]""")
val mockAddressFinder = mock(classOf[AddressFinder])

"Example test" should {
  "should be valid" in {
   val controller = new Match(mockAddressFinder)
   val results = controller.match.apply(FakeRequest(
    POST,
      "test/test",
      FakeHeaders(Seq("Content-type"->("application/json"))),
    json
   ))
   results.onComplete {
    case Success(_) => results.map(s => println("hello" + s.header.status))
    case _=> println("did not work")
  }
}
like image 843
Bob Avatar asked Oct 18 '25 10:10

Bob


1 Answers

you can try this. This is working on me.

   val fakeRequest = FakeRequest(POST, "/someUrl", FakeHeaders(), AnyContentAsJson(Json.parse("""[{"id":"1","address":"my address"}]""")))
   val futureResult: Future[Result] = route(application, fakeRequest).get
   val resultJson: JsValue = contentAsJson(futureResult)(Timeout(2, TimeUnit.SECONDS))
   resultJson.toString mustBe """{"status":"success"}"""
like image 153
user3816201 Avatar answered Oct 20 '25 00:10

user3816201



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!