I have a defined test method chain in test class using Spec2:
def is =
"EntriesServlet with logged user" ^
"POST / request should update entry that user owns" ! updateExistingEntryThatLoggedUserOwns ^
"POST / request should not update non existing entry" ! notUpdateNonExistingEntry ^
"POST / request should not update non owner entry" ! notAllowToUpdateNotOwnedEntry
end
and in these methods I am checking if defined mock were called. But I need to recreate one mock so I could count invocations only for one method not globally.
So what I need is a way to seamlessly define method let's say:
def prepareMocks = {
serviceMock = mock[MyService]
}
that will be executed before each test method so I have clean mock ready before checking my assertions.
I tried with traits BeforeEach
and BeforeExample
from Spec2 but they are not what I am looking for.
You can use case classes to instantiate your mocks and isolate them from other examples being executed at the same time:
import org.specs2._
import specification._
import mock._
class MySpec extends Specification { def is =
"EntriesServlet with logged user" ^
"POST / request should update entry that user owns" ! c().updateExistingEntryThatLoggedUserOwns ^
"POST / request should not update non existing entry" ! c().notUpdateNonExistingEntry ^
"POST / request should not update non owner entry" ! c().notAllowToUpdateNotOwnedEntry ^
end
trait MyService
case class c() extends Mockito {
val service = mock[MyService]
def updateExistingEntryThatLoggedUserOwns = service must not beNull
def notUpdateNonExistingEntry = ok
def notAllowToUpdateNotOwnedEntry = ok
}
}
// here's a similar solution using standardised group names which is a 1.12.3 feature
class MySpec extends Specification { def is =
"EntriesServlet with logged user" ^
"POST / request should update entry that user owns" ! g1().e1 ^
"POST / request should not update non existing entry" ! g1().e2 ^
"POST / request should not update non owner entry" ! g1().e3 ^
end
trait MyService
"POST requests" - new g1 with Mockito {
val service = mock[MyService]
e1 := { service must not beNull }
e2 := ok
e3 := ok
}
}