开发者

How to mock classes in 'src' folder in Grails (unit testing)

I'm trying to write some unit tests for a service in my Grails app. The service, 'MyService', uses a class located in $APP-ROOT/src/groovy/ called 'MyHelperClass'.

In the unit test for MyService, I try to create a mock for MyHelperClass like so:

def myHelperClassMock = mockFor(MyHelperClass)
def myService = new MyService()
myService.myHelperClass = myHelperClassMock.createMock()

This 开发者_如何学Pythongives the error:

Error casting map to com.mycompany.myproject.MyHelperClass, Reason: Could not find matching constructor for: com.mycompany.myproject.MyHelperClass()
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Error casting map to com.mycompany.myproject.MyHelperClass, Reason: Could not find matching constructor for: com.mycompany.myproject.MyHelperClass()
    at grails.test.GrailsMock.createMock(GrailsMock.groovy:91)
    at grails.test.GrailsMock$createMock.call(Unknown Source)
    at com.mycompany.myproject.MyServiceTests.testSomething(MyServiceTests.groovy:17)

This seems to happen only for classes in src/, and appears to work fine for classes in grails-app/services for example. Any idea how I can get it to see the classes in src/?

Thanks!


The code doesn't specify it, but createMock appears to require that the class being mocked have a default (no arguments) constructor.

The normal Grails artifacts under /grails-app all have these, whereas some other class under /src may not.

Adding a default constructor fixed the error when I ran into this.

Also see https://groups.google.com/forum/?fromgroups=#!topic/groovymn/u2Ng_RM224A for a related discussion of this.


This answer should give you the info you need.

Mocking out constructors in Grails

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜