游戏中的模拟对象[2.0] [英] Mock Objects in Play[2.0]

查看:193
本文介绍了游戏中的模拟对象[2.0]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在测试期间提供模拟对象来测试我的Play应用程序。

I want to test my Play application by providing mock objects during a test. Off the top of my head, there are a few ways to go about this.


  1. 在测试期间提供备用路由文件

  2. 使用依赖注入,并在运行时检查全局值

我不知道哪个更可行,或如何去做这些。任何见解将不胜感激。

I am not sure which is more feasible, or how to go about doing them. Any insight would be greatly appreciated.

推荐答案

有第三种方法;创建您的控制器作为一个类或一个特征进行测试。这是一个简单的例子。

There is a third way; create your controller as a class or a trait for testing. Here is a simple example.

你的特质+实现:

Your trait + implementation:

package services

trait MyService {
  def getUser(id:String):User
}

class ConcreteService extends MyService {
  override def getUser(id:String):User = {
  //Do real stuff
  }
}

在您的控制器类中:

package controllers

import services._

class Users(service: MyService) extends Controller {
  def show(id: String) = Action {
    val user = service.getUser(id)
    Ok(views.html.user(user))
  }
}

object Users extends controllers.Users(new ConcreteService()) {}

现在你可以运行一些单元测试..

Now you can run some unit tests..

package test

import controllers.Users
import play.api.test._
import play.api.test.Helpers._

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification

class UsersSpec extends Specification with Mockito {
  val service = mock[MyService]

  "Users controller" should {
    "list users" in {
      //Insert mocking stuff here

      val users = new Users(service)
      val result = users.show("somerandomid")(FakeRequest())
      status(result) must equalTo(OK)
    }
  }
}

这篇关于游戏中的模拟对象[2.0]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆