2017-02-03 74 views
0

我想DRY原則適用於我ScalaTest測試定義。具體而言,我想定義一個抽象測試類定義了一系列測試。所有測試都使用指示要測試的條件的參數調用某個函數。該函數的定義留給擴展類。到目前爲止,這是可行的。覆蓋的測試標籤ScalaTest

接下來,我想標記一個曾經失敗,被定爲「迴歸」測試任何測試,所以如果我是這樣的傾向,我可以只運行這些測試。

但測試最初標記在抽象類。我需要在實現類中覆蓋標籤或添加標籤。

是否有這樣做的一個乾淨的方式?文檔暗示着,但到目前爲止,我無法找到如何做到這一點的例子。

回答

0

我從來沒有找到如何做到這一點的文件,但在那我能弄明白的ScalaDocs足夠的信息。對於那些可能想要做這樣的事情的人來說,這裏是你需要知道的東西:

首先,你會想要定義你自己的特質,你可以混合來獲得這種額外的行爲。它將改寫標籤(定義),就像這樣:

trait _____ extends SuiteMixin with Informing { this: Suite with Informing => 
    // with Informing, etc. is so that you can call info() 
    // to add comments to tests - not strictly needed for this 

    abstract override def tags : Map[String, Set[String]] = { 
    // implementation 
    } 
} 

的實現必須調用super.tags,然後添加任何需要返回之前被添加到所產生的數據結構。結果的關鍵將是測試的名稱,該值將套標籤的字符串。注意:沒有標籤的測試將不會出現,因此您將無法依賴迭代該對象來查找您想要操作的測試。你將不得不打電話this.testNames並迭代。

這裏是我寫的,說明如何退出這個功能的代碼的例子。

abstract override def tags : Map[String, Set[String]] = { 
    val original = super.tags 
    val matching = <list of what to automatically add tags to> 
    if (matching.isEmpty) original 
    else { 
     val tests = this.testNames.toList 
     def extend(result: Map[String, Set[String]], test_list: List[String]) : Map[String, Set[String]] = 
     if (test_list.isEmpty) result 
     else { 
      val matches = (for (p <- matching if (<applicable>)) yield true) contains true 
      if (! matches) extend(result, test_list.tail) 
      else extend( 
      result.updated( 
       test_list.head, 
       result.getOrElse(test_list.head, Set[String]()) 
       + "<tag-to-be-added>"), 
      test.tail 
     ) 
     } 
     extend(original, tests) 
    } 
    } 

希望這可以幫助除我以外的人。

評論如何在更優雅或scala-esque方式做到這一點,值得歡迎和讚賞。