首页 > 解决方案 > 无法从单元测试中的消息文件中读取消息

问题描述

我想从messages文件中读取错误消息,但我不能。我犯了什么错误?

我想从messages文件中读取字符串的代码是

Future {  Ok(Json.toJson(JsonResultError(messagesApi("error.incorrectBodyType")(langs.availables(0))))) }

messages文件_error.incorrectBodyType=Incorrect body type. Body type must be JSON

messagesApi("error.incorrectBodyType") 应该返回Incorrect body type. Body type must be JSON但它返回error.incorrectBodyType

如果我删除双引号,messagesApi(error.incorrectBodyType)则代码无法编译

更新

我添加了一些调试打印,并注意到我在 MessagesApi 中使用的键没有定义。我不知道为什么,因为我已经在messages文件中创建了它们。

println("langs array"+langs.availables)
        println("app.title"+messagesApi.isDefinedAt("app.title")(langs.availables(0)))
        println("error"+messagesApi.isDefinedAt("error.incorrectBodyType")(langs.availables(0)))

印刷

langs arrayList(Lang(en_GB))
app.titlefalse
errorfalse

更新 2 我可能已经找到了问题,但我不知道如何解决它。基本上,我在没有Application. 我是mocking通过调用stubMessagesApi()中定义的messagesApi Helpers.stubControllerComponents,如果我使用Application例如class UserControllerFunctionalSpec extends PlaySpec with OneAppPerSuiteWithComponents然后运行相同的代码app.title并被error定义。似乎没有Application,MessagesApi没有使用该messages文件的实例。

标签: playframework-2.6

解决方案


我能够通过创建一个新的MessagesApi使用实例来解决这个问题DefaultMessagesApi

val messagesApi = new DefaultMessagesApi( //takes map of maps. the first is the language file, the 2nd is the map between message title and description
    Map("en" -> //the language file
      Map("error.incorrectBodyType" -> "Incorrect body type. Body type must be JSON") //map between message title and description
    )
  )
  val controller = new UserController(mockUserRepository,mockControllerComponents,mockSilhouette,messagesApi,stubLangs())

推荐阅读