加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在Spec2中的每个测试之前执行reset方法

发布时间:2020-12-16 08:47:27 所属栏目:安全 来源:网络整理
导读:我在测试类中使用Spec2定义了一个测试方法链: def is = "EntriesServlet with logged user" ^ "POST / request should update entry that user owns" ! updateExistingEntryThatLoggedUserOwns ^ "POST / request should not update non existing entry" !
我在测试类中使用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.但是我需要重新创建一个模拟,所以我只能为一个非全局的方法计算调用.

所以我需要的是一种无缝定义方法的方法,让我们说:

def prepareMocks = {
   serviceMock = mock[MyService]
 }

这将在每个测试方法之前执行,所以我在检查我的断言之前已经准备好了clean mock.

我尝试使用Spec2中的特征BeforeEach和BeforeExample,但它们不是我想要的.

解决方法

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

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
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读