在 ScalaTest 中对集合元素使用 HavePropertyMatcher?
我已经使用 ScalaTest 的 FeatureSpec 有几天了,我试图了解是否可以使用内置匹配器定义以下规范(如果不能,我如何编写合适的自定义匹配器)。
假设我有 Book: 类,
case class Book(val title: String, val author: String)
并且在我的测试中我有一个书籍列表:
val books = List(Book("Moby Dick", "Melville"))
现在,我想指定书籍列表应包含一本标题为“Moby Dick”的书。我想写这样的内容:
books should contain (value with title "Moby Dick")
我似乎无法从文档和代码中弄清楚是否可以在 ScalaTest 中表达此要求。有人遇到过类似的情况吗?
I've been using ScalaTest's FeatureSpec for a couple of days now and I'm trying to understand if it's possible to define the following spec using the built-in matchers (and if not, how I can write a suitable custom matcher).
Suppose I have the class Book:
case class Book(val title: String, val author: String)
and in my test I have a List of books:
val books = List(Book("Moby Dick", "Melville"))
Now, I would like to specify that the books list should contain a book with the title "Moby Dick". I would like to write something like:
books should contain (value with title "Moby Dick")
I can't seem to figure out from the docs and code if it's possible to express this requirement in ScalaTest. Has anyone ran into a similar situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
同时,您可以使用以下自定义匹配器:
然后您可以使用 ScalaTest
Have
匹配器的全部功能来检查对象的字段:最后一个是产生以下输出的失败:
您还可以将匹配器与
and
或or
,使用not
等。In the meantime here's a custom matcher you can use:
Then you can use the full power of the ScalaTest
Have
matcher to inspect the fields of your object:The last one is a failure producing this output:
You can also combine matchers with
and
oror
, usenot
, etc.目前还不行,尽管您将来很快就可以做这样的事情。你现在可以做的是:
Not currently, though you will be able to do something like this very soon in the future. What you can do now is something like:
有一个专门构建的
scalatest
类,名为LoneElement
:https://www.scalatest.org/scaladoc/3.0.8/org/scalatest/LoneElement.html
There is a purposely built
scalatest
class calledLoneElement
:https://www.scalatest.org/scaladoc/3.0.8/org/scalatest/LoneElement.html