在控制器单元测试中存根自定义 TagLib 方法

发布于 2024-11-01 11:26:37 字数 862 浏览 6 评论 0原文

我在自定义标签库中有一个方法,如下所示:

def deleteAction = {attrs ->
    def id = attrs['id']
    def type = attrs['type']
    def clazz = attrs['class']
    def html = new MarkupBuilder(out)
    html.span(class: "${clazz} ui-icon ui-icon-trash {id:'${id}'}")
}

我有一个使用此方法的控制器,我试图将其存根以进行单元测试,所以我有以下内容:

def mockMyTagLib = mockFor(MyTagLib)
    mockMyTagLib.demand.deleteAction(1) {id, type, clazz ->
    def html = new MarkupBuilder(new StringWriter())
    html.span(class: "${clazz} ui-icon ui-icon-trash {id:'${id}'}")
}

controller.metaClass.mn = mockMyTagLib.createMock()

但我不断收到以下内容:

不再调用“deleteAction” 预计此时。结束于 要求。

我在这里做错了什么吗?这是它在控制器中的实际用法:

"${mn.deleteAction(id: it.id, type: 'bookProduct', 'class': 'del-book-product')}"

I have a method in a custom taglib like so:

def deleteAction = {attrs ->
    def id = attrs['id']
    def type = attrs['type']
    def clazz = attrs['class']
    def html = new MarkupBuilder(out)
    html.span(class: "${clazz} ui-icon ui-icon-trash {id:'${id}'}")
}

I have a controller that uses this method and I'm trying to stub it out for a unit test, so I have the following:

def mockMyTagLib = mockFor(MyTagLib)
    mockMyTagLib.demand.deleteAction(1) {id, type, clazz ->
    def html = new MarkupBuilder(new StringWriter())
    html.span(class: "${clazz} ui-icon ui-icon-trash {id:'${id}'}")
}

controller.metaClass.mn = mockMyTagLib.createMock()

But I keep getting the following:

No more calls to 'deleteAction'
expected at this point. End of
demands.

Am I doing something wrong here? Here is it's actual usage in the controller:

"${mn.deleteAction(id: it.id, type: 'bookProduct', 'class': 'del-book-product')}"

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

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

发布评论

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

评论(1

临风闻羌笛 2024-11-08 11:26:38

以下内容来自测试 - 参考文档

...然后指定名称
你想用一个来模拟的方法
可选范围作为其参数。这
范围决定了你有多少次
期望该方法被调用,所以如果
调用次数下降
超出该范围(要么太少
或太多)然后出现断言错误
将被抛出。如果没有范围
指定,默认值为“1..1”
假设,即该方法必须是
只调用一次。

您已指定demand.deleteAction(1),这意味着该方法必须调用一次且仅调用一次。

另外,如果您愿意,您可以随时将模拟设置为宽松,方法是将其指定为mockFor中的第二个参数(默认为严格)

mockFor(class, loose = false)

The following is from Testing - Reference Documentation

... You then specify the name of the
method that you want to mock with an
optional range as its argument. This
range determines how many times you
expect the method to be called, so if
the number of invocations falls
outside of that range (either too few
or too many) then an assertion error
will be thrown. If no range is
specified, a default of "1..1" is
assumed, i.e. that the method must be
called exactly once.

You've specified demand.deleteAction(1) which means that the method must be called once and only once.

Also, if you want, you can always set your mock to be loose by specifying it as the second parameter in mockFor (defaults to strict)

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