我创建了一个类似于下面提到的工作流处理器特性:
import org.scalatestplus.play._
import play.api.mvc._
import play.api.test._
import play.api.test.Helpers._
import org.scalatest.Matchers._
import org.scalamock.scalatest.MockFactory
import utils.OAuthUtils._
import utils.OAuthUtils
import utils.OAuthProcess
import play.api.Application
import scala.concurrent.ExecutionContext
import scala.concurrent.Future
import play.api.libs.json.JsResult
import play.api.libs.json.Json
import play.api.libs.json.JsSuccess
import play.api.libs.json.JsError
import play.api.libs.ws.WS
trait MyProcess[A] {
type B
type C
type D
def stage1(s: String): B
def stage2(b: B)(implicit e: ExecutionContext, app: Application, a: A): Future[C]
def stage3(c: C)(implicit e: ExecutionContext, app: Application, a: A): Future[JsResult[D]]
def process(s: String)(implicit e: ExecutionContext, app: Application, a: A): Future[JsResult[D]] = {
val b = stage1(s)
val f_d = for {
c <- stage2(b)
d <- stage3(c)
} yield d
f_d
}
}
现在我想对这段代码进行单元测试。所以我创建了一个更好的小scalatest scalamock测试套件:
class TestController extends PlaySpec with Results with MockFactory {
"MyController" must {
" testing for method process" in {
running(FakeApplication()) {
implicit val context = scala.concurrent.ExecutionContext.Implicits.global
implicit val s = "implicit String"
implicit val currentApp = play.api.Play.current
case class TestParms(s: String)
abstract class TestProcessor extends MyProcess[TestParms] {
type B = String
type C = String
type D = String
}
implicit val t = stub[TestProcessor]
t.stage1(_: String).when(token).returns(testToken)
(t.stage2(_: String)(_: ExecutionContext, _: Application, _: TestParms)).when(token, context, currentApp, tp).returns({
Future.successful(stage2String)
})
(t.stage3(_: String)(_: ExecutionContext, _: Application, _: TestParms)).when(token, context, currentApp, tp).returns({
Future.successful(Json.fromJson[String](Json.parse(stage3String)))
})
}
}
}
}
我的期望是将此存根设置在不同的类上并测试该类。 Stubs(t.stage2和t.stage3)编译正常,但以下语句不能编译。
t.stage1(_: String).when(token).returns(testToken)
编译器报告以下问题:
overloaded method value when with alternatives: (resultOfAfterWordApplication: org.scalatest.words.ResultOfAfterWordApplication)Unit <and> (f: => Unit)Unit cannot be applied to (String) TestController.scala /play-scala/test/controllers
有人可以帮忙吗?我发现很难为Scala类编写单元测试以及模拟它们。
Build.sbt中的最新版本:
"org.scalatestplus" %% "play" % "1.2.0" % "test",
"org.scalamock" %% "scalamock-scalatest-support" % "3.2" % "test",
答案 0 :(得分:0)
尝试在parens中包装调用
(t.stage1(_: String)).when(token).returns(testToken)
我相信scalac认为您正试图在when
的实例上调用String
(因为这将是t.stage1(_)
返回的内容)。