making domain.save(failOnError:true) fail when doi

2019-09-12 05:16发布

I am purposely causing a cat instance to fail. The following test passes.

  void testSomething() {                            

        Cat.metaClass.save = {

            throw new Exception("Asdasd")
        }

        shouldFail(Exception){

            Cat cat = new Cat(name: "asd")
            cat.save()

        }


        GroovySystem.metaClassRegistry.removeMetaClass(Cat.class)


    }

But, when i set the failOnError property for the save method then this fails. How can i alter the save using metaClass in order to make the save(failOnError:true) throw an exception? I appreciate any help! Thanks!

  void testSomething() {                            

        Cat.metaClass.save = {

            throw new Exception("Asdasd")
        }

        shouldFail(Exception){

            Cat cat = new Cat(name: "asd")
            cat.save(failOnError: true)

        }


        GroovySystem.metaClassRegistry.removeMetaClass(Cat.class)


    }

One alternative to doing the same test is to pass in invalid parameters to the domain instance so that the validation fails and exception is thrown but this will not work in all cases because in some cases the domain instance doesn't require any parameters given by the user. So, in order to simulate the failure of domain save() in this case we will need a way to mock the save failure. So, i appreciate if anyone has answer to how to mock save with or without save params like save(flush:true), save(failOnError:true). Thanks!

1条回答
放我归山
2楼-- · 2019-09-12 06:06

Your first instance of metaClassing the save() is fine.

When trying to metaClass the save(failOnError: true) version, you have to alter your metaClassing statement to match the signature of the actual employed method. A "save()" invocation is not the same as a "save(failOnError:true)" invocation. Try this (I suspect the parameter is strictly typed, so I'm using Map. :

Cat.metaClass.save = { Map map -> 
    throw new Exception("failOnError is true")
}
查看更多
登录 后发表回答