首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Spec2中每次测试前执行reset方法

在Spec2中每次测试前执行reset方法
EN

Stack Overflow用户
提问于 2012-11-26 15:54:05
回答 1查看 1.3K关注 0票数 4

我在使用Spec2的测试类中定义了测试方法链:

代码语言:javascript
复制
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,这样我就可以只计算一个方法的调用次数,而不是全局的。

因此,我需要的是一种无缝定义方法的方法:

代码语言:javascript
复制
 def prepareMocks = {
   serviceMock = mock[MyService]
 }

它将在每个测试方法之前执行,因此我在检查断言之前已经准备好了干净的mock。

我尝试了Spec2的特征BeforeEachBeforeExample,但它们不是我想要的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-11-26 17:51:18

您可以使用case类来实例化您的模拟,并将它们与同时执行的其他示例隔离开来:

代码语言:javascript
复制
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
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13560713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档