Search code examples
scalaplayframeworkplayframework-2.2specs2mockserver

MockServer in org.specs2 tests


I use playframework 2.2.6 scala.

I want to write integration tests for my application. But my application requests some service by http and I want to mock it with mockServer. But I don't know when to start and stop mockServer cause tests use futures

@RunWith(classOf[JUnitRunner])
class AppTest extends Specification with Around {

    def around[T](t: => T)(implicit e: AsResult[T]): Result = {

        val port = 9001

        val server = new MockServer()

        server.start(port, null)

        val mockServerClient = new MockServerClient("127.0.0.1", port)

        // mockServerClient rules

        val result = AsResult.effectively(t)

        server.stop()

        result
    }

    "Some test" should {

        "some case" in new WithApplication {

            val request: Future[SimpleResult] = route(...).get

            status(request) must equalTo(OK)

            contentAsString(request) must contain(...)
        }

        "some other case" in new WithApplication {
            //
        }
    }
}

With this code I have java.net.ConnectException: Connection refused: /127.0.0.1:9001. And I can't do this without server.stop cause that server must be run in different tests.


Solution

  • I found solution, I looked source code of WithApplication (it extends Around) and wrote abstract class WithMockServer:

    abstract class WithMockServer extends WithApplication {
    
      override def around[T: AsResult](t: => T): Result = {
    
        Helpers.running(app) {
    
          val port = Play.application.configuration.getInt("service.port").getOrElse(9001)
          val server = new MockServer(port)
    
          val mockServerClient = new MockServerClient("127.0.0.1", port)
    
          // mockServer rules
    
          val result = AsResult.effectively(t)
          server.stop()
          result
        }
      }
    }
    

    And in each test cases I replaced in new WithApplication with in new WithMockServer