title: Grails testing a failing domain save in service
body: <p>I've a Grails (3+) service where a domain object is retrieved from the DB, modified , and then updated in the DB.</p>
  
  <pre><code>class MyService {
      def modifyObject(String uuid) {
          def md = MyDomain.findByUuid(uuid)
          md.someField = true
          if (!md.save()){ 
              throw new MyException()
          }
      }
  }
  </code></pre>
  
  <p>Now <strong>I need to test this service method with a negative test</strong>, to be sure that the exception is thrown. But I can't figure out how to <em>force</em> a failing <code>save</code> in the service method.</p>
  
  <pre><code>@TestFor(MyService)
  @Mock(MyDomain)
  class MyServiceSpec extends Specification {
  
      void "test An exceptionl situation was found"() {
          given: "An uuid"
              def md = new MyDomain(uuid: "123")
              md.save(failOnError: true)
  
          when: "service is called"
              service.modifyObject("123")
  
          then: "An exception is thrown"
              thrown MyException
      }
  }
  </code></pre>
  
  <p>Obviously, re-defining the service method in a more functional way (the object is passed directly to the method, modified and returned <em>without save</em> .e.g <code>MyDomain modifyObject(MyDomain md)</code>) will be a good solution since I could create an invalid <em>ad hoc</em> object outside or even invalidate it after the method execution.</p>
  
  <p>But the question is: "<strong>is there a way to test the service code <em>as is</em>?</strong>"</p>