2

Possible Duplicate:
Mock Objects in Play[2.0]

I am learning Scala and playframework, while developing a simple application. One thing frustrates me. I have strong C# background, and used to unit testing in classical terms - mocking underlying services and test only the code in the given class.

And the question is - how to unit test a playframework application written is Scala? The way of testing proposed by playframework manual - is an integration tests, which are good, but not the thing I need. Particulary - how to mock the data access layer?

Community
  • 1
  • 1
Mike G.
  • 700
  • 5
  • 22
  • 2
    http://stackoverflow.com/questions/10053424/mock-objects-in-play2-0/10114621#10114621 – Blake Pettersson Nov 02 '12 at 07:55
  • http://www.playframework.org/documentation/2.0/ScalaTest – 0xAX Nov 02 '12 at 12:25
  • @shk This is an integration tests example. It tests application as a whole, using real database server. I asked about unit testing, which is quite different approach. The link above leads to a good answer. – Mike G. Nov 03 '12 at 09:32

1 Answers1

2

Creating mock objects is usually needed when you can not isolate your tests by having to load too many dependencies in your application before testing. You don't have that limitation when you test your data access layer in Play 2.X. Therefor, all you need to do is to use Specs2 Specification and load the in-memory database using FakeApplication(additionalConfiguration = inMemoryDatabase()

A complete test could then be written like this:

class ProjectSpec extends Specification {

  "Project model" should {

    "be created with id and name" in {
      running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {
        val beforeCount = Project.count
        val project = Project.create(Project("Test name", "Test description"))
        project.id must beSome
        project.name must equalTo("Test name")
        Project.count must equalTo(beforeCount + 1L)
      }
    }
  }
}
Ola Wiberg
  • 1,679
  • 1
  • 13
  • 14