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

在ScalaTest中组合测试夹具的更好方法

发布时间:2020-12-16 18:36:14 所属栏目:安全 来源:网络整理
导读:我们使用 loan pattern测试夹具.利用这种模式创建测试运行所需的“种子数据”.当测试依赖于数据时以下 "save definition" should {"create a new record" in withSubject { implicit subject = withDataSource { implicit datasource = withFormType { impli
我们使用 loan pattern测试夹具.利用这种模式创建测试运行所需的“种子数据”.当测试依赖于数据时以下

"save definition" should {
"create a new record" in withSubject { implicit subject =>
  withDataSource { implicit datasource =>
    withFormType { implicit formtype =>

        val definitn = DefinitionModel(-1,datasource.id,formtype.id,subject.role.id,Some(properties))
    }
  }
}

whereSubject,withDataSource,withFormType是测试装置,分别从数据库返回subject,dataSource,formType数据. withDataSource fixture需要隐式地使用subject.构建DefinitionModel需要datasource.id和formtype.id.所以根据测试的数据要求调用这样的数据构建器夹具会产生很多嵌套的夹具情况.有没有更好的方法来“组合”/构建这样的灯具?

解决方法

特征

trait是你的朋友.组成是特征所涵盖的要求之一.

组成特征

从Scala Test Docs开始

Composing fixtures by stacking traits

In larger projects,teams often end up with several different fixtures
that test classes need in different combinations,and possibly
initialized (and cleaned up) in different orders. A good way to
accomplish this in ScalaTest is to factor the individual fixtures into
traits that can be composed using the stackable trait pattern. This
can be done,for example,by placing withFixture methods in several
traits,each of which call super.withFixture.

例如,您可以定义以下特征

trait Subject extends SuiteMixin { this: Suite =>

  val subject = "Some Subject"

  abstract override def withFixture(test: NoArgTest) = {
    try super.withFixture(test) // To be stackable,must call super.withFixture
    // finally clear the context if necessary,clear buffers,close resources,etc.
  }
}

trait FormData extends SuiteMixin { this: Suite =>

  val formData = ...

  abstract override def withFixture(test: NoArgTest) = {
    try super.withFixture(test) // To be stackable,etc.
  }
}

然后,您可以将这些特征混合到您的测试环境中,只需将它们混合在一起:

class ExampleSpec extends FlatSpec with FormData with Subject {

    "save definition" should {
        "create a new record" in {

            // use subject and formData here in the test logic            

        }
    }

}

可堆叠的特征

有关Stackable Traits Pattern的更多信息,请参阅this article

(编辑:李大同)

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

    推荐文章
      热点阅读