WaZ
WaZ

Reputation: 1757

Testing custom constraints in Grails App

I have the following as my unit test:

void testCreateDealer() {
      mockForConstraintsTests(Dealer)
      def _dealer= new Dealer( dealerName:"ABC",
                            Email:"[email protected]",
                            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)
            }
     )

Upvotes: 0

Views: 776

Answers (2)

ataylor
ataylor

Reputation: 66069

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.

Upvotes: 0

Armand
Armand

Reputation: 24353

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.

Upvotes: 2

Related Questions