Jules Olléon
Jules Olléon

Reputation: 6888

Spock: creating mocked objects at run-time

I have a class Foo that has a method Bar makeBar(String id). As you can guess, makeBar creates a new Bar object with the id id. Bar has a getter for id.

For the purpose of my test I need to mock Foo. I would like the mocked makeBar method to create mocked Bar objects for which the getter returns the correct id (the one that was given to makeBar).


So to be clear, I want to create a mocked instance foo of Foo such that

foo.makeBar(someId)

returns a mocked Bar object bar for which

bar.getId() == someID

Is there a way to do this with Spock, or should I stub everything?

Upvotes: 1

Views: 1503

Answers (1)

Peter Niederwieser
Peter Niederwieser

Reputation: 123920

Yes, it's possible to have a mock return other mocks. This will do the trick:

Foo foo = Mock()

foo.makeBar(_) >> { String id ->
    Bar bar = Mock()
    bar.getId() >> id
    bar
}

I've published the complete and runnable code here: http://webconsole.spockframework.org/?id=40001.

Upvotes: 4

Related Questions