Search code examples
unit-testingscalaplayframework-2.0mockitospecs2

Play Framework 2 scala specs2 mockito, how do I write a mocking unit test


So the play framework talks about having specs2 and specs2 having mockito

I want to use mockito to write a test where the template that the controller invokes is a mockito mock.

All the doc's I've found so far are java implementations where you call the mock static function and give it the Mocked class as a generics argument.

From what I can tell the mock function is not exposed by default within a specification, so how do I create a mockito mock?

Please give an example that includes both creating the mock, and asserting the mock is called with certain arguments


Solution

  • After a lot of googling and hair pulling I came up with the following

    package test
    
    import org.specs2.mutable._
    
    import play.api.test._
    import play.api.test.Helpers._
    
    import org.specs2.mock._
    import org.mockito.Matchers
    
    class ToTest {
      def go(a:String) = {
        "other"
      }
    }
    
    class MockSpec extends Specification with Mockito {
      "Mock" should {
          "work" in {
            //assemble
            val m = mock[ToTest]
            m.go(anyString) returns "tested"
    
            //act
            val result = m.go("test")
    
    
            //assert
            result must equalTo("tested")
            there was one(m).go(Matchers.eq("test"))
          }
      }
    }