NPE when working with mock objects

156 views
Skip to first unread message

Kenny

unread,
Feb 2, 2011, 10:59:56 AM2/2/11
to Spock Framework - User
Hi,

I have the following feature method to test a Grails domain object:

def "test something"() {
setup:
mockDomain(Header)
def detail = Mock(Detail)
def header = new Header().addToDetails(detail)
expect:
...
}

The test failed at the line with "addToDetails". The error is:

N/A
java.lang.NullPointerException
at java.lang.Class.isAssignableFrom(Native Method)
at
grails.test.MockUtils.addDynamicInstanceMethods_closure75_closure107(MockUtils.groovy:
848)

If I change the code to "def detail = new Detail()", everything would
work fine. Does anyone know what the problem is?

Thanks!
Kenny

Hans Westerbeek

unread,
Feb 2, 2011, 11:14:05 AM2/2/11
to spockfr...@googlegroups.com
the grails mockDomain method doesn't mock those addTo methods.
What you need is something like this
mockDomain(Header)
def header = new Header(details: [])
header.details.add(new Detail())

I don't think you have to mockDomain(Detail) in your use case (from
what I can see here)

> --
> You received this message because you are subscribed to the Google Groups "Spock Framework - User" group.
> To post to this group, send email to spockfr...@googlegroups.com.
> To unsubscribe from this group, send email to spockframewor...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/spockframework?hl=en.
>
>

Kenny

unread,
Feb 2, 2011, 11:54:36 AM2/2/11
to Spock Framework - User
Grails's mockDomain method does mock the addTo methods. If I use "new
Header().addToDetails(new Detail())", the code runs fine. But if I use
"new Header().addToDetails(Mock(Detail))", it fails with the NPE
error. So it must have something to do with the mock object.

Peter Niederwieser

unread,
Feb 2, 2011, 12:18:52 PM2/2/11
to spockfr...@googlegroups.com
The problem might be related to the fact that Spock mocks created for Groovy classes don't automatically implement any GroovyObject methods except for getMetaClass(). Maybe this can be improved. I guess the problem wouldn't occur if Detail was an interface or a Java class.

Cheers,
Peter

Reply all
Reply to author
Forward
0 new messages