我们有使用贷款模式的测试装置。利用这种模式创建测试运行所需的“种子数据”。当测试依赖于数据,例如:
"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))
}
}
}其中withSubject、withDataSource、withFormType分别是从数据库返回subject、dataSource、formType数据的测试夹具。withDataSource夹具隐式地要求subject。构建DefinitionModel需要datasource.id和formtype.id。因此,根据测试的数据需求,调用这样的数据构建器夹具会产生许多嵌套的夹具情况。是否有更好的方法来“编写”/structure这样的装置?
发布于 2018-05-06 09:48:13
@Nader Hadji Ghanbari给出的答案仍然成立。我只想补充一下,自从3.x.x版的scalatest之后,这些特性就改变了名称。从迁移指南复制:
覆盖 withFixture的米辛性状 ( 4)在3.0.0中,withFixture方法从Suite移到了一个新的性状TestSuite上。这样做是为了给在withFixture中具有不同签名的AsyncTestSuite方法留出空间。如果将withFixture方法分解为单独的“套件混合”特性,则需要将"Suite“更改为"TestSuite”,将"SuiteMixin“更改为"TestSuiteMixin”。例如,鉴于2.2.6中的这一特性: 属性YourMixinTrait扩展了SuiteMixin { this:=>套件抽象覆盖def withFixture(测试: NoArgTest):结果={ // .} 您需要添加"Test“前缀,如下所示: 特质YourMixinTrait扩展TestSuiteMixin { this: TestSuite =>抽象覆盖def withFixture(test: NoArgTest):TestSuite={ // .}
发布于 2015-03-04 04:01:17
性状
trait是你的朋友。组合是trait非常好地涵盖的需求之一。
组成性状
来自Scala测试文档
按堆叠特性组合夹具 在较大的项目中,团队通常会得到几个不同的固定装置,测试类需要在不同的组合中使用,并且可能以不同的顺序初始化(和清理)。在ScalaTest中实现这一目标的一个好方法是将单个固定装置分解为可以使用可堆叠的特征模式组合的特征。例如,这可以通过将withFixture方法放置在几个特征中来完成,每个特征都调用super.withFixture。
例如,您可以定义以下trait的
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, must call super.withFixture
// finally clear the context if necessary, clear buffers, close resources, etc.
}
}然后,只需将这些trait混合到测试上下文中,就可以将它们带到测试上下文中:
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
}
}
}堆叠性状
有关可叠加性状模式的更多信息,您可以参考这篇文章
https://stackoverflow.com/questions/28845975
复制相似问题