I've a Grails (3+) service where a domain object is retrieved from the DB, modified , and then updated in the DB.
class MyService {
def modifyObject(String uuid) {
def md = MyDomain.findByUuid(uuid)
md.someField = true
if (!md.save()){
throw new MyException()
}
}
}
Now I need to test this service method with a negative test, to be sure that the exception is thrown. But I can't figure out how to force a failing save
in the service method.
@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
}
}
Obviously, re-defining the service method in a more functional way (the object is passed directly to the method, modified and returned without save .e.g MyDomain modifyObject(MyDomain md)
) will be a good solution since I could create an invalid ad hoc object outside or even invalidate it after the method execution.
But the question is: "is there a way to test the service code as is?"
Aucun commentaire:
Enregistrer un commentaire