如何在 Specs2 中重用描述*和*匹配器的值?

发布于 2024-12-11 06:54:37 字数 556 浏览 0 评论 0 原文

我目前正在使用 scalaz 中的 |> 来实现以下目的:

(4 |> (s => (s + " is smaller than 10" ! (s < 10 must beTrue)))

这允许我在测试用例的描述中重用对象的 .toString 。但由于 Specs2 似乎支持某种复杂的东西,例如通过扫描 src 文件夹从测试源中提取内容——他们一定考虑过这个特定的用例。

还有 GivenWhenThen 等内容,但看起来非常冗长。

那么如何重用同一个对象来进行描述和匹配器呢?我认为我的解决方案是可以接受的,但括号困扰着我。实际上它看起来像这样:

(Set((1,2),(3,4)) |> (s => s + " has Set(1,2) as component of 1" ! (graph.componentOf(s,1) must_== Set(1,2)))) 

I'm currently using |> from scalaz for achieving the following:

(4 |> (s => (s + " is smaller than 10" ! (s < 10 must beTrue)))

This allows me to reuse the .toString of an object inside the description of the test case. But since Specs2 seems to support kind of complicated stuff like extracting things from the source of the tests by scanning the src folder --- they must have thought about this particular use case.

There's also the Given, When, Then stuff but it looks extremely verbose.

So how do I reuse the same object for description and matcher? I think my solution is acceptable but the parenthesis are bugging me. In reality it looks like this:

(Set((1,2),(3,4)) |> (s => s + " has Set(1,2) as component of 1" ! (graph.componentOf(s,1) must_== Set(1,2)))) 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

望喜 2024-12-18 06:54:37

当示例的正文非常接近描述时,您可以使用“auto-examples":

"some examples"     ^
{ 4 must be_<(10) } ^
{ 5 must be_<(10) }

在这种情况下,使用 sbt 执行时,示例的主体将直接用作描述:

[info] some examples
[info] + 4 must be_<(10)
[info] + 5 must be_<(10)

请注意,我将期望写为 4 必须be_<(10) 而不是 (4 < 10) 必须为True,因为如果出现问题,失败消息会更加明确:

14 is not less than 10
        vs
the value is false

如果您想使用以下命令增强失败消息 :甚至更多信息,您还可以使用 aka 运算符:

 (4 < 10) aka "four < ten" must beTrue

最后,还有一个更简单版本的 Give-When-Then,您可以在其中简单地 重用示例的描述

 "4 is smaller than 10" !  { (s: String) => 
   s.split(" ").head.toInt must be_<(10) 
 }

When the body of the example is very close to the description you can just use "auto-examples":

"some examples"     ^
{ 4 must be_<(10) } ^
{ 5 must be_<(10) }

In that case, the body of the example is directly used as a description when executed with sbt:

[info] some examples
[info] + 4 must be_<(10)
[info] + 5 must be_<(10)

Note that I wrote the expectations as 4 must be_<(10) instead of (4 < 10) must beTrue because the failure message is going to be more explicit if something goes wrong:

14 is not less than 10
        vs
the value is false

If you want to enhance a failure message with even more information you can also use the aka operator:

 (4 < 10) aka "four < ten" must beTrue

Finally, there is a simpler version of Given-When-Then, where you can simply reuse the description of an example:

 "4 is smaller than 10" !  { (s: String) => 
   s.split(" ").head.toInt must be_<(10) 
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文