2017-07-19 87 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}”, –