Search code examples
groovyproxy-classes

cast closure map to object with a private constructor in groovy


I am using groovy to create some mock classes for a test case. I am basically creating dummy objects where all the methods return null so that i can run my testcase.

I am using the following syntax:

MessageFactory.instance = ["getMessage": {a,b,c,d -> "dummy"}] as MessageFactory

So here i am trying to overwrite the singleton instance with my on fake factory object. The problem is that MessageFactory's constructor happens to be a private method. This gives me an illigal access exception when i run the code above. Is there a away i can create a proxy in groovy and overcome the private constructor issue?


Solution

  • If you have access to the MessageFactory, and are willing to modify it, then you use the standard dependency-injection solution, as detailed here: mock singleton ..Though it's not particularly Groovy.

    Otherwise, the best workaround I've found is to override the method(s) on the singleton instance itself, like so:

    @Singleton
    class Test{
        def method(){"Unmocked method called"}
    }
    
    
    def test = Test.instance
    test.metaClass.method = {-> null}
    
    test.method() // Now returns null
    

    Naturally, as a singleton, this instance doesn't change (at least in theory)... So, overriding methods in this manner is effectively global.

    Edit: Or you can use GMock, which supports constructor mocking (among other things).