首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在使用编译时注入的应用程序中测试控制器

如何在使用编译时注入的应用程序中测试控制器
EN

Stack Overflow用户
提问于 2018-06-06 04:42:22
回答 1查看 375关注 0票数 1

我的应用程序使用编译时注入。加载器的定义如下(代码片段):

class AppLoader extends ApplicationLoader { ...}

class AppComponents (context: Context) extends BuiltInComponentsFromContext(context) {
...

//within this I have created instances of my controller and created a route
    lazy val userController = new UserController(userRepository, controllerComponents, silhouetteJWTProvider)

lazy val router = new Routes(httpErrorHandler, homeController,userWSRoutes, countController,asyncController, assets)

}

UserController类有一个signupUser Action

@Singleton
class UserController @Inject()(
userRepo: UsersRepository,cc: ControllerComponents, silhouette: Silhouette[JWTEnv])(implicit exec: ExecutionContext) extends AbstractController(cc){
...

def signupUser = silhouette.UserAwareAction.async{ implicit request => {
...
}
}

我想测试signupUser Action,但是我不知道怎么做。我已经创建了以下规范类,但我被困在如何编写规范和测试它的问题上。

class UserControllerSpec extends PlaySpec {


    "User signup request with non-JSON body" must {
      "return  400 (Bad Request) and the validation text 'Incorrect body type. Body type must be JSON'" in {

//I want to create instance of a `FakeRequest` annd pass it to UserController.signupUser. I should test a Future[Result] which I should then assert.

//How do I get instance of userController which I created in my Apploader? I don't want to repeat/duplicate the code of AppLoader here.

      }
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-06 07:59:55

您的ApplicationLoader中的现有组件可以是directly instantiated within tests。Mixin WithApplicationComponents特征和覆盖def components: BuiltInComponents

override def components: BuiltInComponents = new YourComponents(context)

下面是您的测试的一个示例实现:

import org.scalatestplus.play._
import org.scalatestplus.play.components.OneAppPerSuiteWithComponents
import play.api.BuiltInComponents
import play.api.mvc.Result
import play.api.libs.json.Json
import play.api.test.Helpers._
import play.api.test._
import scala.concurrent.Future

class UserControllerSpec extends PlaySpec with OneAppPerSuiteWithComponents {

  override def components: BuiltInComponents = new YourComponents(context)

  "User signup request with non-JSON body" should {

    "return  400 (Bad Request) and the validation text 'Incorrect body type. Body type must be JSON'" in {

      val Some(result): Option[Future[Result]] =
        route(
          app, 
          FakeRequest(POST, "/signup").withJsonBody(Json.parse("""{"bad": "field"}"""))
        )

      status(result) mustBe BAD_REQUEST
    }
  }
}

Helpers.stubControllerComponents对于单元测试控制器非常有用。下面是一个示例,说明如何使用它来实现相同的测试,而不必处理ApplicationLoader

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import controllers.UserController
import org.scalatest.mockito.MockitoSugar
import org.scalatestplus.play._
import play.api.libs.json.Json
import play.api.test.Helpers._
import play.api.test._

class UserControllerSpec extends PlaySpec with MockitoSugar {

  "User signup request with non-JSON body" should {

    "return  400 (Bad Request) and the validation text 'Incorrect body type. Body type must be JSON'" in {

      implicit val actorSystem = ActorSystem()
      implicit val materializer = ActorMaterializer()

      val controller = new UserController(
        mock[UsersRepository]
        Helpers.stubControllerComponents(playBodyParsers = Helpers.stubPlayBodyParsers(materializer)),
        mock[Silhouette[JWTEnv]]
      )

      val result = 
        call(
          controller.signupUser, 
          FakeRequest(POST, "/signup").withJsonBody(Json.parse("""{"bad": "field"}"""))
        )

      status(result) mustBe BAD_REQUEST
    }
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50708624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档