playframework 2.6 と play-slick 0.8.0 を使用しています。
アクションコード:
def addCompany = Authenticated {
DBAction(parse.json) {
implicit rs => {
val newCompany = rs.request.body
val result = CompanyTable.insert(newCompany.as[Company])(rs.dbSession)
if(result > 0)
Ok("{\"id\":"+result+"}")
else
Ok("New company was not created.")
}
}
}
Action は、有効なセッションをチェックするだけの Action と、要求本文に有効な JSON オブジェクトが必要な DBAction を組み合わせたものです。
テストコード:
"should create a Company from a Json request" in new InMemoryDB {
val newCompany = Company(name = "New Company1")
val fr = FakeRequest(POST, "/company")
.withSession(("email", "bob@villa.com"))
.withHeaders(CONTENT_TYPE -> "application/json")
.withJsonBody(Json.toJson(newCompany))
val action = controllers.CompanyController.addCompany
val result = action(fr).run
status(result) should be_==(OK)
(contentAsJson(result) \ "id").as[Long] should be_>(1L)
}
InMemoryDB クラスは、メモリ内データベースが事前設定された単なる FakeApplication です。
私が抱えている問題は、テストを実行すると、[Invalid Json] というメッセージを含むボディ コンテンツを含む結果が常に 400 になることです。同じJSONボディコンテンツでcurlを使用してサービスを呼び出すと、サービスが機能し、IDが返されます。