You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@groovy.apache.org by "Søren Berg Glasius (GR8Conf EU)" <sb...@gr8conf.org> on 2016/02/09 10:57:48 UTC

Trait methods cannot be overriden by metaClass

Hi,

We have run into an issue where methods in Traits cannot be be overriden with the metaClass

This is an example:

package demo

import spock.lang.Specification

class FooSpec extends Specification {

    void 'test replacing Widget.getMagicNumber'() {
        setup:
        Widget.metaClass.getMagicNumber = { ->
            2112
        }

        expect:
        // this one fails
        new Widget().getMagicNumber() == 2112
    }

    void 'test replacing Gadget.getMagicNumber'() {
        setup:
        Gadget.metaClass.getMagicNumber = { ->
            2112
        }

        expect:
        // this one passes
        new Gadget().getMagicNumber() == 2112
    }
}

class Widget implements Magician {}

trait Magician {
    int getMagicNumber() {
        42
    }
}

class Gadget {
    int getMagicNumber() {
        42
    }
}

This is causing a lot of headaches for Grails 3 projects, especially where metaClass overrides are used in tests. It has been reported as a bug here: https://issues.apache.org/jira/browse/GROOVY-7500 but has not yet been commented on by the Groovy team.

I hope this will raise awareness of the problem.

Best regards,
Søren Berg Glasius
GR8Conf Europe organizing team

GR8Conf ApS
Mobile: +45 40 44 91 88, Web: www.gr8conf.eu, Skype: sbglasius 
Company Address: Buchwaldsgade 50, 5000 Odense C, Denmark
Personal Address: Hedevej 1, Gl. Rye, 8680 Ry, Denmark
--- GR8Conf - Dedicated to the Groovy Ecosystem