Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 704
The Trav Avatar asked Jul 10 '13 06:07

The Trav


People also ask

What is mocking in Scala?

ScalaMock is a native, open-source Scala mocking framework written by Paul Butcher that allows you to mock objects and functions. ScalaMock supports three different mocking styles: Function mocks. Proxy (dynamic) mocks. Generated (type-safe) mocks.

What is mocking in Junit?

While doing unit testing using junit you will come across places where you want to mock classes. Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls.


1 Answers

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"))
      }
  }
}
like image 109
The Trav Avatar answered Oct 23 '22 04:10

The Trav