Testing custom constraints in Grails App

风格不统一 提交于 2020-01-06 08:33:32

问题


I have the following as my unit test:

void testCreateDealer() {
      mockForConstraintsTests(Dealer)
      def _dealer= new Dealer( dealerName:"ABC",
                            Email:"abc-motors@global.com",
                            HeadOffice:"",
                            isBranch:false)
       assertFalse _dealer.validate()

    }

But when I run the test I get the following error:

No signature of method: static com.myCompany.Dealer.findByDealerNameIlike() is applicable for argument types: (java.lang.String) values: [ABC]

I use some custom constraints in my domain class. How Can I test this?

 static constraints = {
     dealerName(blank:false, validator:
            { val, obj ->
                      def similarDealer = Dealer.findByDealerNameIlike(val)
                      return !similarDealer || (obj.id == similarDealer.id)
            }
     )

回答1:


Try changing mockForConstraintsTests() to mockDomain() - you're using a Dealer.findX() method in the constraint, which relies on the Dealer domain.

Incidentally, the test will still fail unless you've created a similar dealer in the setUp() method of the test class.




回答2:


In unit tests, even with mockDomain, the id attribute of domain objects is not set automatically, or auto-incremented. All of the domain objects you create will have an id of null unless you explicitly set it.

Your test is probably failing because the test obj.id == similarDealer.id is true, since they both have id: null. Try setting the id attribute of your mocked dealer objects.



来源:https://stackoverflow.com/questions/2590906/testing-custom-constraints-in-grails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!