Play 2.0中的存根控制器

时间:2012-11-08 07:40:16

标签: scala testing mocking playframework-2.0 stub

我正在尝试Mock Objects in Play[2.0]的例子,但不幸的是我没有成功。

我有一个使用UserModel的UsersController。

trait UserModel extends ModelCompanion[User, ObjectId] {
 // ...
}

接下来,抽象控制器

abstract class UsersController extends Controller {

  val userModel: UserModel

  def sayHello = Action(parse.json) { request =>
    // return a play Action. Doesn't use userModel
  }


  // Other methods

}

在路径文件中,我用这种方式调用方法说Hello:

  

POST / hello controllers.Users.sayHello

在测试目录中,我使用UserModel mock创建了UsersController的子类。

package controllers

import org.specs2.mock.Mockito

object UserControllersTest extends UsersController with Mockito {
  val userModel = mock[models.UserModel]
}

现在,主要部分。我按照之前提到的页面中的Jacob Groundwater示例创建了一个Spec测试。在为FakeApplication提取参数时,我包含了对UserControllersTest的调用。

package controllers

import org.specs2.mutable.Specification

import play.api.libs.json.Json
import play.api.test._
import play.api.test.Helpers._

class UsersSayHelloSpec extends Specification {

  running(FakeApplication()) {

    "Users.SayHello" should {

      def sendJson(jsonMap: Map[String, String], shouldBeCorrect: Boolean) = {
        running(new FakeApplication(
          additionalPlugins = Seq("controllers.UserControllersTest"))) {
          // Preapration 
          val jsonRequisition = Json.toJson(jsonMap)
          val Some(result) = routeAndCall(FakeRequest(POST,
              "/hello",
              FakeHeaders(Map("Content-Type" -> Seq("application/json"))),
              jsonRequisition))

            // ...
        }
      }

      "Not process a empty String" in {
        sendJson(Map.empty[String, String], false)
      }

      // Other tests calling sendJson ...
    }

  }

}

但是,当我运行测试时,我收到此错误消息:

[info] Users.SayHello should
[error] ! Not process a empty String
[error]     PlayException: Cannot load plugin [Plugin [controllers.UserControllersTest] cannot been instantiated.] (Application.scala:171)
...
[error] play.api.Application.<init>(Application.scala:158)
[error] play.api.test.FakeApplication.<init>(Fakes.scala:141)
[error] controllers.UsersSayHelloSpec$$anonfun$1$$anonfun$apply$5.sendJson$1(UsersSayHelloSpec.scala:20)
[error] controllers.UsersSayHelloSpec$$anonfun$1$$anonfun$apply$5$$anonfun$apply$26.apply(UsersSayHelloSpec.scala:46)
[error] controllers.UsersSayHelloSpec$$anonfun$1$$anonfun$apply$5$$anonfun$apply$26.apply(UsersSayHelloSpec.scala:46)

其中UsersSayHelloSpec.scala:20引用我称之为运行方法的行。

所以我的问题是:我做错了什么?

0 个答案:

没有答案