如何全局配置Scala Concurrent Eventually的默认超时时间?
如何为ScalaTest Eventually设置全局默认超时
当然可以实现!ScalaTest的Eventually是通过隐式的PatienceConfig来控制默认超时和轮询间隔的,我们只需要自定义一个trait来统一配置这个隐式值,就能让所有测试共享默认超时,同时保留单个测试覆盖的灵活性,完美符合DRY原则。
步骤1:创建自定义的全局Eventually trait
我们可以定义一个自己的trait,继承原生的Eventually并覆盖默认的隐式PatienceConfig,把超时设置为你需要的全局默认值(比如2秒):
import org.scalatest.concurrent.Eventually import org.scalatest.time.{PatienceConfig, Seconds, Span} trait DefaultEventually extends Eventually { // 全局默认超时:2秒,你可以根据需求调整 override implicit val patienceConfig: PatienceConfig = PatienceConfig( timeout = Span(2, Seconds), interval = Span(100, org.scalatest.time.Milliseconds) // 可选:同时设置默认轮询间隔 ) }
步骤2:在测试类中使用自定义trait
把原来测试类中继承的Eventually替换成我们的DefaultEventually,这样所有测试都会自动使用全局默认超时,不需要再手动写timeout(2.seconds):
class AsyncCharacterTest extends WordSpec with Matchers with DefaultEventually with BeforeAndAfterAll with ResponseAssertions { "Should provide the character from that where just created" should { val character = Character(name = "juan", age = 32) service.createIt(character) // 这里直接用eventually,自动使用全局2秒超时 eventually { responseAs[Character] shouldBe character } } }
步骤3:单个测试覆盖默认超时
如果某个测试需要特殊的超时时间,依然可以像之前那样手动传入timeout参数来覆盖全局配置,完全不影响灵活性:
eventually(timeout(5.seconds)) { // 这个测试单独使用5秒超时,不受全局配置影响 responseAs[Character] shouldBe character }
原理说明
Eventually的eventually方法会优先使用你显式传入的PatienceConfig(比如timeout(5.seconds)本质是创建了一个自定义的PatienceConfig),如果没有传入,就会使用隐式作用域中的patienceConfig。我们通过自定义trait提供全局的隐式配置,就实现了默认值的统一管理,同时保留了单个测试的自定义能力。
内容的提问来源于stack exchange,提问作者juan garcia
相关产品推荐
相关产品推荐

