【问题标题】:unable to read messages from messages file in unit test无法从单元测试中的消息文件中读取消息
【发布时间】:2018-06-12 15:37:34
【问题描述】:

我想从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 messagesApi,通过调用Helpers.stubControllerComponents 中定义的stubMessagesApi(),如果我使用Application 运行相同的代码,例如class UserControllerFunctionalSpec extends PlaySpec with OneAppPerSuiteWithComponents,则定义app.titleerror。似乎没有Application 的实例,MessagesApi 没有使用messages 文件。

【问题讨论】:

    标签: playframework-2.6


    【解决方案1】:

    我能够通过使用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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 2011-01-12
      • 2021-03-11
      • 1970-01-01
      • 2022-01-03
      • 2011-06-30
      • 1970-01-01
      相关资源
      最近更新 更多