Executing the reset method before each test in Spec2

I have a specific chain of test methods in a 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 check if mock has been defined. But I need to recreate one layout, so I could only count calls for one method non-globally.

So, I need a way to easily define let say method:

  def prepareMocks = { serviceMock = mock[MyService] } 

which will be executed before each test method so that I have a clean layout before checking my claims.

I tried with the BeforeEach and BeforeExample from Spec2, but they are not what I am looking for.

+4
source share
1 answer

You can use case classes to instantiate your mocks and isolate them from other examples that run simultaneously:

 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 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 } } 
+2
source

All Articles