2017-07-19 85 views
0

斯卡拉specs2匹配我想檢查一個字符串是否包含另一個同時提供使用「又名」標籤。例如:斯卡拉specs2匹配與「又名」

"31 west 23rd street, NY" aka "address" must contain("11065") 

這種失敗

address '31 west 23rd street, NY' doesn't contain '11065'. 

不過,我想指定11066是郵政編碼。如:

"31 west 23rd street, NY" aka "address" must contain("11065") aka "zip code" 

哪一個不行。

任何想法如何實現? 所需的結果,我想到的是:

address '31 west 23rd street, NY' doesn't contain zip code '11065'. 

下面是一個可能的解決方案,但我不喜歡它,因爲它不是SPEC2本地和只支持字符串:

def contain(needle: String, aka: String) = new Matcher[String] { 
    def apply[S <: String](b: Expectable[S]) = { 
    result(needle != null && b.value != null && b.value.contains(needle), 
     s"${b.description} contains $aka '$needle'", 
     s"${b.description} doesn't contain $aka '$needle'", b) 
    } 
} 

回答

1

我不認爲這是一個適用於所有匹配者的解決方案。在這種情況下,你可以重複使用aka機械

def contain(expected: Expectable[String]): Matcher[String] = new Matcher[String] { 
    def apply[S <: String](e: Expectable[S]): MatchResult[S] = 
    result(e.value.contains(expected.value), 
     s" ${e.value} contains ${expected.description} ${expected.value}", 
     s" ${e.value} does not contain ${expected.description}", 
     e) 
} 

"31 west 23rd street, NY" aka "address" must contain("11065" aka "the zip code") 

這顯示

31 west 23rd street, NY does not contain the zip code '11065' 
+0

該解決方案比我稍微好一點,因爲它使用的原又名方法。我修改了第5行以適應我的要求:「$ {e.description}不包含$ {expected.description}」, –