Search code examples
scalaspecs2

Specs2 running a matcher outside of the test class in an anonymous inner class


I am running the following test:

class FooTest extends SpecWithJUnit with MockServer {

"Foo" should {
 "fail" in new ctx {

    givenAListenerThatAlwaysFailsWhenExcecuted()
    foo.runMethodThatInvokesAListener
  }
 }
} 

trait MockServer extends BeforeAfterAll with MustMatchers {

  private val wireMockServer = new WireMockServer(wireMockConfig().port(9000))

  def givenAListenerThatAlwaysFailsWhenExcecuted() = {
    val listener = new RequestListener {
    override def requestReceived(request: Request, response: Response): Unit = {
    true must beFalse
  }
}
  wireMockServer.addMockServiceRequestListener(listener)
  listener
}

 override def beforeAll(): Unit = wireMockServer.start()
 override def afterAll(): Unit = wireMockServer.stop()
}

When I run it, I see the exception in the console but the test itself is not failing. How do I get it to fail?


Solution

  • You must use MustThrownMatchers instead of MustMatchers so that any failed expectation such as true must beFalse get thrown out of new ctx { ... }.

    Otherwise true must beFalse is just a simple MatchResult[Boolean] value which is happily created inside the body of the anonymous ctx class.