为什么我不能测试是否定义了类的实例

问题描述 投票:0回答:2

我有一个辅助类,它创建另一个类的实例

class TestEnv {
val questionsController = new QuestionsController(...)
}

我是单元测试QuestionsController并创建了一个基本的测试用例

class QuestionsControllerUnitSpec extends PlaySpec with BeforeAndAfterAll with BeforeAndAfterEach with OneAppPerSuiteWithComponents{

  override def beforeEach() = {
    println("------------new test -----------------")
  }


  override def components: BuiltInComponents = new BuiltInComponentsFromContext(context) with NoHttpFiltersComponents {

    import play.api.mvc.Results
    import play.api.routing.Router
    import play.api.routing.sird._


    lazy val router: Router = Router.from({
      case GET(p"/") => defaultActionBuilder {
        Results.Ok("success!")
      }
    })




  }

  "Question Controller " should {
    "be created" in {
      val testEnv = new TestEnv(components = components)
      val qc:QuestionsController = testEnv.questionsController
      qc mustBe defined //I get compilation error 

    }
  }


}

我收到以下编译错误

Error:(52, 10) could not find implicit value for parameter definition: org.scalatest.enablers.Definition[controllers.QuestionsController]
      qc mustBe defined
Error:(52, 10) not enough arguments for method mustBe: (implicit definition: org.scalatest.enablers.Definition[controllers.QuestionsController])org.scalatest.Assertion.
Unspecified value parameter definition.
      qc mustBe defined

我查看了mustBeMustMatchers.class的定义。它被定义为def mustBe(right : org.scalatest.words.DefinedWord)(implicit definition : org.scalatest.enablers.Definition[T]) : org.scalatest.Assertion = { /* compiled code */ }

为什么我收到错误。

scalatest playframework-2.6
2个回答
0
投票

如果我们提供defined特征的隐式实现,则Definition matcher语法可以与用户定义的类型一起使用。例如,假设我们有一个用户定义的类

class Foo {
  val bar = 3
}

我们提供隐含的定义

implicit val fooDefinition = new Definition[Foo] {
  override def isDefined(foo: Foo): Boolean = foo.bar != null
}

然后我们可以使用defined语法

(new Foo()) mustBe defined

如果提供了类似的Definition[QuestionsController]隐式实现,则应解决编译器错误。


0
投票

如果可以提供更准确的答案,我很乐意接受不同的答案。我想我正在测试错误的东西。我正在做的类似于声明一个整数并检查整数是否存在!相反,我应该检查整数的值。

关于matchers,更多信息请访问http://doc.scalatest.org/3.0.1/#org.scalatest.MustMatchers。有关Definition的更多信息,请访问http://doc.scalatest.org/3.0.1/#org.scalatest.enablers.Definition

© www.soinside.com 2019 - 2024. All rights reserved.