tags:

views:

314

answers:

1

In my attempt to mock an object in Groovy using the mock.interceptor package:

def mock = new MockFor(TheClass);
mock.demand.theMethod{ "return" }
mock.use {
    def underTest = new TheClass()
    println underTest.theMethod()
}

The problem I have is when creating TheClass() in the use{ block, it uses the actual constructor which, in this circumstance, I'd rather it not use. How can I create an instance of this class so I can test the method I do care about, theMethod, without needing to use the constructor?

Using EasyMock/CE, mocks can be made without using the constructor, but am curious how to achieve that in Groovy.

+1  A: 

I recently saw a presentation by the author of GMock and it has some hooks to allow "constructor" mocking which I think is what you are after.

e.g.

 def mockFile = mock(File, constructor('/a/path/file.txt'))

This library differs from that "built in" to groovy, however it looked very well written, with some thought put into the kinds of things you want to mock and more importantly the error messages you would get when tests should fail.

I think this is what you are after. I would say use constructor mocking with care - it could be a smell that you should inject a Factory object, but for some things it looked to work well.

TimM