Benjamin Muschko
Benjamin Muschko

Reputation: 33436

Simulate throwing an exception for mocked domain class

I am in the process of writing unit tests for a Grails service class. The service class uses multiple domain classes. Creating mocks for the domain classes works like a charm using the mockDomain method. Even the code paths that test if a domain object can be saved correctly (domain validation) can be written easily. However, in my code I also wrapped domain object operations with a try/catch block that handles the exception cases. Is there a way to simulate that a domain operation throws an exception? This can easily be done with Mock frameworks like Mockito (thenThrow) or EasyMock (andThrow) but I am primarily looking for a way native to Grails. I'd be open to frameworks that complement the Grails testing framework.

Upvotes: 0

Views: 1006

Answers (1)

Steve Goodman
Steve Goodman

Reputation: 1196

It's simple using Groovy's metaclassing. For this example, I'll say one of your domain classes is Foo.

void testFooThrowsException(){
    def fooInstance = new Foo()
    fooInstance.metaClass.methodToTest = {arg1, arg2->
        throw new CustomException("I'm an exception")
    }

    shouldFail CustomException, {fooInstance.methodToTest("val1", "val2")}
}

Once you've modified the metaclass of an instance, that instance will have the modified behavior for it's full lifecycle. Read more on metaclassing on the Groovy site. It's one of the coolest parts of Groovy, IMO.

Upvotes: 1

Related Questions