Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

scala - Mock Objects in Play[2.0]

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. Provide an alternative route files during testing
  2. Use Dependency Injection, and check for a global value at runtime

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  }
}

In your controller class:

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)
    }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...