English 中文(简体)
Groovy 1.8.6 正在使用不正确的元分类方法
原标题:Groovy 1.8.6 Incorrect metaClassed Method Being Used

当用圣杯2.0.1进行重构时,我碰巧碰到了这个问题,但我把这个问题的基本原理拖到一个直接的格朗维1.8.6的测试中,结果还是失败了。我发现它是因为我的方法没有参数,而我把它换成了一个参数。当我改变执行生产代码时,我的测试没有失败。这很奇怪,因为我在测试中的元拼图设置为不接受参数,但当我在一个参数中通过时,它仍然在响应我的生产代码。在下面的例子中,我想知道为什么引用第二个元分类而不是第一个参数。它不接受任何参数,而且你可以看到我通过一个参数。如果你切换了元分类的顺序,那它就会正常工作,但是由于方法的签名不同,这里的顺序应该很重要。任何关于为什么发生这种情况的洞察都会非常感激。

import groovy.util.GroovyTestCase

class FirstTest extends GroovyTestCase {

    void testStuff() {
        def object = new Object()
        object.metaClass.someMethodName = {Object obj ->
            "ONE"
        }
        object.metaClass.someMethodName = {
            "TWO"
        }

        def result = object.someMethodName(new Object())

        assert "ONE" == result //result is equal to "TWO" in this case
    }

}

<强 > EDIT

似乎我上面的代码 可能更混乱 比帮助 所以这里是实际代码。

原生产代码:

def create() {
    render(view: "create", model: [domains: Domain.myCustomListMethod().sort{it.cn}])
}

原始测试代码 :

@Test
void createShouldIncludeAListOfAllDomainsInModel() {
    def directory = GldapoDirectory.newInstance(
            "", [
                    url: "http://url.com",
                    userDn: "someUserName",
                    password: "superSecretPassword"
            ])
    controller.session.userDirectory = directory
    Domain.metaClass. static .myCustomListMethod = {
        [[cn:"1"], [cn:"2"]]
    }

    controller.create()

    assert [[cn:"1"], [cn:"2"]] == controller.modelAndView.model.domains
}

然后,我更新了生产代码,在session.user Statey 中通过。 我的测试仍然没有经过修改,尽管没有设置接收参数:

def create() {
    render(view: "create", model: [domains: Domain.list(session.userDirectory).sort{it.cn}])
}
最佳回答

默认关闭需要一个参数(类对象的参数),即使没有被宣布(可以通过默认变量 it 进入)

所以,你的第二个关闭 压倒了第一个

问题回答

暂无回答




相关问题
Groovy - how to exit each loop?

I m new to Grails/Groovy and am trying to find a node in a an xml file; I ve figured out how to iterate over all of them, but I want to exit the loop when the target node is found. I ve read that ...

Eclipse Spring Builder set properties with Groovy beans

I typically use groovy to construct simple bean but the Spring IDE plugin to eclipse fails to build when I try to set a property that is generated by groovy without an explicit setter. For example, ...

How can I get this snippet to work?

I d like to port a little piece of code from Ruby to Groovy, and I m stuck at this: def given(array,closure) { closure.delegate = array closure() } given([1,2,3,4]) { findAll { it > 4} ...

Changing the value in a map in Groovy

This is about a very basic program I m writing in Groovy. I have defined a map inside a method: def addItem() { print("Enter the item name: ") def itemName = reader.readLine() print(...

Is functional Clojure or imperative Groovy more readable?

OK, no cheating now. No, really, take a minute or two and try this out. What does "positions" do? Edit: simplified according to cgrand s suggestion. (defn redux [[current next] flag] [(if flag ...

热门标签