Question

I am writing a spock unit test that tests a controller method.

The controller action under test instantiates a new domain instance object and calls validate on it before it saves. Is there anyway of mocking the call to domainInstance.validate() so I can make it return whatever I want? Or do I have to hide this instanciation and saving behind a service method to achieve this?

I do this this way, because within the context of a unit test for a controller, the constraints of a domain object should not be involved. I test those elsewhere (in the MyDomainClassTests, obviously). If I wanted to take those into into account my test would be an integration test.

Was it helpful?

Solution 2

After a while I have come to the conclusion that what I wanted is rather tricky. If you're in a scenario where you don't have to use mockDomain(), you could add a groovy metaclass method and it's implementation (return true or false, whichever you want)

If you do need mockDomain() because you need to mock pre-existing instances you are out of options, at least for now because mockDomain() and fiddling with metaclass methods that mockDomain actually provides will not mix.

OTHER TIPS

If you didn't place the validate on the domain instance itself, but rather in a service, you could let your controller take a Service in its constructor (or rather an interface of a service). Let that service handle the validation.

Now for your unittest of that controller, you would pass in a Mock of that interface(service) to the controller and configure the mock to return whatever you want.

For .net i can recommend Moq (http://code.google.com/p/moq/)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top