0

我正在使用带有 play framework 2.5 的 Silhouette v4.0 库。并且一直在尝试使用 play specs2 编写测试代码。但是,我的测试类出现以下错误,如下所示。

错误信息

[error] could not find implicit value for parameter env: com.mohiva.play.silhouette.api.Environment[utils.auth.DefaultEnv]
        .withAuthenticator[DefaultEnv](identity.loginInfo)
                                      ^

这是测试类

package controllers

import com.google.inject.AbstractModule
import org.joda.time.DateTime
import org.specs2.specification.Scope
import org.specs2.matcher._
import org.specs2.mock._
import play.api.test._
import play.api.libs.json._
import play.api.libs.json.Json
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.mailer.{ MailerClient, Email }
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.inject.bind
import com.mohiva.play.silhouette.test._
import com.mohiva.play.silhouette.api._
import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository
import com.mohiva.play.silhouette.api.util._
import com.mohiva.play.silhouette.impl.providers._
import net.codingwell.scalaguice.ScalaModule
import utils.auth.DefaultEnv

class TestControllerSpec extends PlaySpecification with Mockito {
  "case" in new Context {
    new WithApplication(application) {
      val request = FakeRequest(POST, "/api/test")
        .withAuthenticator[DefaultEnv](identity.loginInfo) // <-
      val result = route(app, request).get
      status(result) must be equalTo OK
    }
  }

  trait Context extends Scope {
    val identity = User(
      loginInfo = LoginInfo(..)
      ..
    )

    implicit val env = FakeEnvironment[DefaultEnv](Seq(identity.loginInfo -> identity))

    class FakeModule extends AbstractModule with ScalaModule {
      def configure() = {
        bind[Environment[DefaultEnv]].toInstance(env)
      }
    }

    lazy val application = new GuiceApplicationBuilder()
      .overrides(new FakeModule)
      .build
  }
}

还有一些与此类类似的其他测试类能够正确编译和执行。这是范围的隐含问题。因此,我尝试导入与另一个能够正确编译的测试类相同的内容。但是,仍然无法编译。缺少一些进口?

4

1 回答 1

1

正如编译器所述,您缺少一个隐式值。使用以下内容,这是根据 Silhouette 的规格之一建模的:

class TestControllerSpec extends PlaySpecification with Mockito {
  "the POST request" should {    
    "return an OK response" in new Context {
      new WithApplication(application) {
        val identity = User(LoginInfo(...))
        implicit val env = FakeEnvironment[DefaultEnv](Seq(identity.loginInfo -> identity))
        val request = FakeRequest(POST, "/api/test")
          .withAuthenticator(identity.loginInfo)

        val result = route(app, request).get
        status(result) must be equalTo OK
      }
    }
  }

  trait Context extends Scope {
    ...
  }
}
于 2017-09-26T20:01:55.733 回答