Spock Unit Test: How to mock a controller method in Grails

722 views
Skip to first unread message

Dean Del Ponte

unread,
Jul 27, 2011, 4:51:36 PM7/27/11
to Spock Framework - User
Simple question for you spock gurus. I asked this question on the
Grails mailing list, but received no response.

How do I mock a controller method? For example:

Controller Code:

class MyController {

def apps = {
// do stuff
}

def proxy = {
// do stuff
}
}

I would like to mock out the controller method "apps" so it returns a
predefined value.

I've attempted:
controller.apps(_) >> "test"

but this has no affect.

Any suggestions?

Thanks!

Dean Del Ponte

Luke Daley

unread,
Jul 27, 2011, 7:22:55 PM7/27/11
to spockfr...@googlegroups.com

It's not a method, it's a closure, so you really want…

controller.getApps() >> { "test" }

Peter Niederwieser

unread,
Jul 27, 2011, 7:39:11 PM7/27/11
to spockfr...@googlegroups.com

This will still return a string. To return a closure, use:

controller.apps >> { { -> "test" } } // or getApps()

Cheers,
Peter

Luke Daley

unread,
Jul 27, 2011, 7:47:37 PM7/27/11
to spockfr...@googlegroups.com

So Spock understands closures as a mechanism for lazy evaluation?

e.g.

class T {

def getFoo() {
1
}
}

T t = Mock()
def bar = 1
t.getFoo() >> { bar }

t.foo == 1
bar = 2
t.foo == 2

?

Peter Niederwieser

unread,
Jul 28, 2011, 8:25:10 AM7/28/11
to spockfr...@googlegroups.com
On 28.07.2011, at 01:47, Luke Daley wrote:
> On 28/07/2011, at 9:39 AM, Peter Niederwieser wrote:
>>
>> This will still return a string. To return a closure, use:
>>
>> controller.apps >> { { -> "test" } } // or getApps()
>
> So Spock understands closures as a mechanism for lazy evaluation?

Yes, I guess you could call it lazy initialization. It allows you to perform an arbitrary action in response to a method call. A common use case is throwing an exception.

Cheers,
Peter

Dean Del Ponte

unread,
Jul 28, 2011, 9:37:37 PM7/28/11
to Spock Framework - User
The following also seems to work:

controller.metaClass.apps = {
return "test"
Reply all
Reply to author
Forward
0 new messages