Stefan Kendall
Stefan Kendall

Reputation: 67832

Stubbing all methods of a groovy class?

Is there an easy way to stub ALL methods of a groovy class? In one of my tests, I need to make sure a certain code path doesn't touch a service at all.

That is, I want to mock every method like this:

[meth1: {-> fail(msg)},
 meth2: {-> fail(msg)...}] as MyService

Is there an easy way to stub and intercept all methods of all argument types and perform some uniform action like this?

Upvotes: 1

Views: 362

Answers (2)

Dónal
Dónal

Reputation: 187539

If MyService is an interface you can do this:

MyService stub = {Object[] args -> fail(msg)} as MyService

I'm not sure if this works when MyService is a class

Upvotes: 2

Christoph Metzendorf
Christoph Metzendorf

Reputation: 8078

The most simple way I can think of is something like this:

MyService.metaClass.invokeMethod { String name, args ->
  assert false
}

Upvotes: 5

Related Questions