문제

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.

도움이 되었습니까?

해결책 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.

다른 팁

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/)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top