我想通过从scala工作表运行它来测试一个类。运行此测试脚本时:
import ping.GcmRestServer
val server = new GcmRestServer("AIzaSyCOn...")
server.send(List("dcGKzDg5VOQ:APA91bHNUDaBj01th..."), Map(
"message" -> "Test Message",
"title" -> "Test Title"
))
测试类GcmRestServer是
package ping
import play.api.Logger
import play.api.libs.ws.WS
import play.api.libs.json.Json
/**
* Created by Lukasz on 26.02.2016.
*/
class GcmRestServer(val key: String) {
def send(ids: List[String], data: Map[String, String]) = {
import play.api.Play.current
import scala.concurrent.ExecutionContext.Implicits.global
val body = Json.obj(
"registration_ids" -> ids,
"data" -> data
)
WS.url("https://android.googleapis.com/gcm/send")
.withHeaders(
"Authorization" -> s"key=$key",
"Content-type" -> "application/json"
)
.post(body)
.map { response => Logger.debug("Result: " + response.body)}
}
}
给出以下结果:
import ping.GcmRestServer
server: ping.GcmRestServer = ping.GcmRestServer@34860db2
java.lang.RuntimeException: There is no started application
at scala.sys.package$.error(test.sc2.tmp:23)
at play.api.Play$$anonfun$current$1.apply(test.sc2.tmp:82)
at play.api.Play$$anonfun$current$1.apply(test.sc2.tmp:82)
at scala.Option.getOrElse(test.sc2.tmp:117)
at play.api.Play$.current(test.sc2.tmp:82)
at ping.GcmRestServer.send(test.sc2.tmp:16)
at #worksheet#.get$$instance$$res0(test.sc2.tmp:4)
at #worksheet#.#worksheet#(test.sc2.tmp:19)
有人可以解释一下我做错了什么,以及如何解决这个问题?
答案 0 :(得分:6)
第import play.api.Play.current
行需要正在运行的Play应用程序。
我从未使用过scala工作表,但似乎也存在同样的问题。
在测试中,解决方案是运行假应用程序,如written in the documentation。
答案 1 :(得分:0)
您正在使用需要运行播放应用程序的播放 WS。只需用这样的代码开始:
import play.api.libs.ws.WS
import play.api.{Play, Mode, DefaultApplication}
import java.io.File
import play.api.Logger
import play.api.libs.json.Json
import scala.concurrent.ExecutionContext.Implicits.global
class GcmRestServer(val key: String) {
val application = new DefaultApplication(
new File("."),
Thread.currentThread().getContextClassLoader(),
None,
Mode.Dev
)
def send(ids: List[String], data: Map[String, String]) = {
val body = Json.obj(
"registration_ids" -> ids,
"data" -> data
)
WS.client(application).url("https://android.googleapis.com/gcm/send")
.withHeaders(
"Authorization" -> s"key=$key",
"Content-type" -> "application/json"
)
.post(body)
.map { response => Logger.debug("Result: " + response.body)}
}
}
或者,如果您不想使用 WS.Client(application)
,您可以运行 Play.start(application)
,使用 import play.api.Play.current
导入它,然后 WS.url
将起作用。