如何使用ScalaTest“包含所有的"在两个名单上? [英] How to use ScalaTest "contain allOf" on two lists?

查看:41
本文介绍了如何使用ScalaTest“包含所有的"在两个名单上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个 ScalaTest 匹配器来检查一个列表是否包含所有需要的元素(在另一个列表中给出),但也可能是其他元素.

I was looking for a ScalaTest matcher to check that a list contains all of the needed elements (given within another list), but that may also be others.

contain allOf 要求获取两个固定元素,由于某种原因,其余为可变参数.

contain allOf demands to get two fixed elements, for some reason, the rest as varargs.

我可以做一个这样的解决方法,但它非常难看:

I can do a workaround like this, but it's tremendously ugly:

val list = List(1,2,3,4)
val wanted = List(1,2,3)
list should contain allOf ( wanted.head, wanted.tail.head, wanted.tail.tail  :_* )    // ugly workaround

为了提供一个列表作为匹配,有 contain theSameElementsAs.但是,它不允许探测值中包含无关元素(我认为).

For giving a list as the match, there is contain theSameElementsAs. However, it does not allow extraneous elements to be in the probed value (I think).

所以:

  • 我错过了什么吗?
  • 为什么声明 allOf 必须在前面给出两个固定元素(即为什么不直接传递可变参数?)
  • 是否应该有 theSameElementsAndMaybeMoreThan 方法(大概有更好的名字)?
  • am I missing something?
  • why is allOf declared in the way that it must be given two fixed elements in the front (i.e. why not just pass varargs?)
  • should there be theSameElementsAndMaybeMoreThanmethod (presumably with a better name)?

我尝试过的一些代码:

val list = List.empty[String]
//list should contain allOf("a")         // does not compile
list should contain allOf("a","b")
list should contain allOf("a","b","c")

val wanted = List("a","b","c")
//list should contain allOf( wanted )    // does not compile
list should contain allOf( wanted.head, wanted.tail )   // compiles, but tests the wrong thing; against List(head,List(tail))

文档:

Scala 2.11.4,ScalaTest 2.2.1

Scala 2.11.4, ScalaTest 2.2.1

我可能最终会使用类似的东西:

I probably end up using something like:

wanted.foreach( list should contain(_) )

然而,这对我来说似乎不像内置集合结构那样可读(should 是嵌入的).

However, this does not seem as readable to me (the should is kind of embedded) as the built-in collection constructs.

推荐答案

Bill Venners 在 ScalaTest 邮件列表中这样说:

Bill Venners had this to say on the ScalaTest mailing list:

是的,我们不想拖延 2.0 版本来添加它,但是有自从添加了它.我相信我们将它添加到 master 中,而不是 2.2.x分支.无论如何,语法看起来像:

Yes, we didn't want to hold up the 2.0 release to add that, but have since added it. I believe we added it to master, though, not the 2.2.x branch. Regardless, the syntax looks like:

xSet 应该包含 allElementsOf (ySet)

链接到消息.

这篇关于如何使用ScalaTest“包含所有的"在两个名单上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆