无法在单元测试中从消息文件中读取消息

unable to read messages from messages file in unit test

我想从 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") 应该 return Incorrect body type. Body type must be JSON 但它 returns 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 实例的情况下设置我的测试用例。我通过调用 Helpers.stubControllerComponents 中定义的 stubMessagesApi()mocking messagesApi,如果我 运行 使用 Application 相同的代码,例如 class UserControllerFunctionalSpec extends PlaySpec with OneAppPerSuiteWithComponents 那么 app.titleerror 被定义。似乎没有 Application 的实例,MessagesApi 没有使用 messages 文件。

我能够通过使用 DefaultMessagesApi

创建 MessagesApi 的新实例来解决问题
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())