我在使用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在这些方法中,我检查是否调用了定义的mock。但是我需要重新创建一个mock,这样我就可以只计算一个方法的调用次数,而不是全局的。
因此,我需要的是一种无缝定义方法的方法:
def prepareMocks = {
serviceMock = mock[MyService]
}它将在每个测试方法之前执行,因此我在检查断言之前已经准备好了干净的mock。
我尝试了Spec2的特征BeforeEach和BeforeExample,但它们不是我想要的。
发布于 2012-11-26 17:51:18
您可以使用case类来实例化您的模拟,并将它们与同时执行的其他示例隔离开来:
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
}
}https://stackoverflow.com/questions/13560713
复制相似问题