Question

I have two class:

class Foo {
    String doSomething(String a = 'Not working') {
        return a
    }
}

And I want to replace 'doSomething' in a test but it dosent work

@Test
void testMethodIWannaTest() {
    Foo.metaClass.doSomething = {String a -> return 'Working'}

    assert new Foo().doSomething() == 'Working' //THIS TEST FAIL, return 'Not Working'
}

If I remove the optional param, it works.

Did someone know how to fix this ?

*I know the test doesn't really make sens, it's just to show my point

What do I do wrong ? Is it possible to do it without using 'mockFor' ?

Was it helpful?

Solution

Setting a default parameter generates two methods:

String doSomething()         { doSomething( 'Not working' ) }
String doSomething(String a) { a }

So try setting the no-arg function (as that's the one you're going to call:

Foo.metaClass.doSomething = { -> doSomething( 'Working' ) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top