RE: [grails-user] Mocks

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view

RE: [grails-user] Mocks

Dierk König
this should go to the Groovy user list...

> Several questions about (mock) testing:
> 1.) Is it possible to mock a class, e.g. File, with the MockFor
> class or any other Groovy supported mechanism?
>     new MockFor(File.class)
> does not work, because Groovy does not know which constructor it
> should chose.

Hm, not sure. Have to look into that.
Mocks should work for all instances of a class and the ctors
shouldn't be affected...
Have you looked into the test cases for the Mock facility?

> 2.) How to mock a method with a closure? Example:
>     class Foo {
>         def bar() {
>             dirs = []
>             new File('.').eachDir{ dir -> if( == 'foo')
> dirs << dir }
>             return dirs
>         }
>     }
> More generally spoken, how can I test what is the logic inside
> the closure when the object the closure was called on has been
> mocked? Thinking a javaish way does not help me, because I would
> not use anonymous classes the way I would use it in Groovy...
> *idea*
> This way?
>     def mock = new MockFor(File.class) // assuming that it would
> work in some way
>     mock.demand.eachDir() { c -> ['foo', 'bar'].each{ c(it) } }
>     mock.use{
>         assertEquals(['foo'], new Foo().bar() }
>     }
> Any ideas?

Technically, your idea should work but
you shouldn't go overboard with mocks or you end up
adding too much logic to the tests.
(BTW: it looks like stubs would be sufficient here)

What is your test goal? Asserting that the closure that is
passed to eachDir works as expected?
In that case, refactor your code, assign the closure to a
property and test it in isolation.
Otherwise, simply return a static value.

Thanks for raising the interesting question about
closure arguments in mocked method calls

To unsubscribe from this list please visit: