使用 Mocha 进行模拟排序

发布于 2024-08-28 06:46:25 字数 707 浏览 8 评论 0原文

如何模拟数组的排序并期望 lambda 表达式?

这是我的问题的一个简单例子:

# initializing the data
l = lambda { |a,b| a <=> b }
array = [ 1, 2, 3, 4, 5 ]
sorted_array = [ 2, 3, 8, 9, 1]

# I expect that sort will be called using the lambda as a parameter
array.expects(:sort).with( l ).returns( sorted_array )

# perform the sort using the lambda expression
temp = array.sort{|a,b| l.call(a,b) }

现在,一开始我预计这会起作用;但现在我已经意识到了。但是,我收到以下错误:

- expected exactly once, not yet invoked: [ 1, 2, 3, 4, 5 ].sort(#<Proc:0xb665eb48>)

我意识到这不起作用,因为 l 没有作为参数传递给 l。但是,还有其他方法可以完成此代码试图完成的任务吗?

注意:我已经弄清楚如何解决我的问题,但不知道如何执行上述操作。我会将其保留,以防其他人遇到类似的问题。

干杯, 约瑟夫

How can I mock an array's sort expect a lambda expression?

This is a trivial example of my problem:

# initializing the data
l = lambda { |a,b| a <=> b }
array = [ 1, 2, 3, 4, 5 ]
sorted_array = [ 2, 3, 8, 9, 1]

# I expect that sort will be called using the lambda as a parameter
array.expects(:sort).with( l ).returns( sorted_array )

# perform the sort using the lambda expression
temp = array.sort{|a,b| l.call(a,b) }

Now, at first I expected that this would work; however, I got the following error:

- expected exactly once, not yet invoked: [ 1, 2, 3, 4, 5 ].sort(#<Proc:0xb665eb48>)

I realize that this will not work because l is not passed as a parameter to l. However, is there another way to do what this code is trying to accomplish?

NOTE: I have figured out how to solve my issue without figuring out how to do the above. I will leave this open just in case someone else has a similar problem.

Cheers,
Joseph

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

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

发布评论

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

评论(1

不回头走下去 2024-09-04 06:46:25

使用块来模拟方法可能会非常令人困惑。关键之一是明确你想要测试什么行为。我无法从您的示例代码中准确判断您要测试的内容。但是,您可能会找到 Mocha::Expectation#yields 的文档(甚至 Mocha::Expectation#multiple_yields)很有用。

Mocking methods with blocks can be quite confusing. One of the keys is to be clear about what behaviour you want to test. I can't tell from your sample code exactly what it is that you want to test. However, you might find the documentation for Mocha::Expectation#yields (or even Mocha::Expectation#multiple_yields) useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文