scala – 在specs2中,有条件地执行从函数返回的结果的子测试,可
在specs2中,表达子测试模式的正确方法是什么,只有在其“父”测试返回结果而不抛出异常时才执行?
我有一个函数maybeGiveMeAThing,它可以返回Thing,也可以抛出异常. 通话看起来像这样: val事:Thing = maybeGiveMeAThing(“foo”,“bar”“baz”) 我想用一组输入测试一下,也许给我成功返回一个Thing而不抛出异常,并使用返回的Thing,做进一步的测试以确保为给予maybeGiveMeAThing的参数返回正确的Thing. 我当前设置测试的方式,如果对maybeGiveMeAThing的调用抛出异常,则整个测试套件中止.这将是我更喜欢的逻辑: >如果成功返回了Thing,请继续进行一组分析事物内容的子测试 我现有的测试代码大致如下: // ... "with good parameters" in { var thing: Thing = null "return a Thing without throwing an exception" in { thing = maybeGiveMeAThing("some","good","parameters","etc.") } should not(throwA[Exception]) "the Thing returned should contain a proper Foo" in { thing.foo mustBe "bar" } //... etc ... } // ... } …虽然这感觉就像是从正确的方式做到这一点.什么是正确的方法? 解决方法
一种可能性是在@alexwriteshere回答中使用条件:
"parent test" in { val thing: Option[Thing] = maybeGiveMeAThing("foo","bar" "baz") thing match { case Some(thing) => "child test 1" in ok "child test 2" in ok case None => "skipped tests" in skipped } } 但是,您需要在None情况下添加一个Example,以便in方法的块具有可接受的类型. 这种方法的一大缺点是规范在定义时正在执行.这意味着: >如果maybeGiveMeAThing存在异常,则整个规范将会爆炸 另一种选择是使用Step表示任何先前的失败将跳过所有下一个示例: class MySpec extends mutable.Specification { "This is a test with a thing" >> { lazy val thing: Option[Thing] = maybeGiveMeAThing("foo","bar" "baz") "the thing should be ok" >> { thing must beOk } step(stopOnFail = true) "other examples with thing" >> { "ex1" >> ok "ex2" >> ok } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |