playframework-2.6 - 无法从单元测试中的消息文件中读取消息
问题描述
我想从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
文件的实例。
解决方案
我能够通过创建一个新的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())
推荐阅读
- python - Python 3 Tkinter - 尝试通过一个按钮阻止多个窗口打开
- r - 弹出窗口中的传单 html 小部件(迷你图)
- docker - Kubelet 运行失败:无法创建证书签名请求:未经授权
- php - 哪些 PHP 错误级别会停止执行?
- php - MySQLi 查询循环太慢
- angular - Karma-Jasmine 测试执行错误 HeadlessChrome
- c# - C# - 如何检查用户是否使用 HttpWebRequest 登录到网络
- node.js - 如何通过bunyan CLI工具日志将管道保存到日志文件而不是json格式
- java - 试图将 setEditable 设置为 false 但出现错误
- windows - 如何在批处理文件中捕获调用的输出?