在ScalaTest中组合测试夹具的更好方法
|
我们使用
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.所以根据测试的数据要求调用这样的数据构建器夹具会产生很多嵌套的夹具情况.有没有更好的方法来“组合”/构建这样的灯具? 解决方法
特征
组成特征 从Scala Test Docs开始
例如,您可以定义以下特征 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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
