本文介绍了进行集成测试时使domain.save(failOnError:true)失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我故意使cat实例失败.以下测试通过.

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)


    }

但是,当我为save方法设置failOnError属性时,此操作将失败.我如何使用metaClass更改保存以使save(failOnError:true)引发异常?感谢您的帮助!谢谢!

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)


    }

执行相同测试的另一种方法是将无效参数传递给域实例,以使验证失败并引发异常,但这在所有情况下均不起作用,因为在某些情况下域实例不需要任何参数由用户给出.因此,在这种情况下,为了模拟域save()的失败,我们将需要一种模拟保存失败的方法.因此,如果有人对如何模拟保存或不保存参数(如save(flush:true),save(failOnError:true))进行模拟,我将不胜感激.谢谢!

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!

推荐答案

您的metaClassing的第一个实例save()很好.

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

当尝试对save(failOnError:true)版本进行metaClass时,必须更改metaClassing语句以匹配实际使用的方法的签名. "save()"调用与"save(failOnError:true)"调用不同.试试这个(我怀疑参数是严格输入的,所以我正在使用Map.:

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")
}

这篇关于进行集成测试时使domain.save(failOnError:true)失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 18:49
查看更多