简体   繁体   中英

Grails: Unit test domain class constraint gives wrong result

I'm trying to write unit tests for my domain class to test constraints but I got unexpected result. Here is my domain class:

class Student {
    String firstName
    String lastName

    static constraints = {
        firstName blank:false,minSize:2,maxSize:20,validator: { val, obj ->
                      def similarUser = Student.findByFirstNameIlikeAndLastNameIlike(obj.firstName, obj.lastName)
                      if(!similarUser || obj.id == similarUser.id){
                      return ['Student.invalid.unique.message']
                      }
                    }
        lastName blank:false, minSize:2,maxSize:20
    }

}

and here is my unit tests:

@TestFor(Student)
@Mock(Student)
class StudentTests {
    def st

    @Before
    void setUp(){       
        mockForConstraintsTests(Student)        
        st=new Student(firstName:"FerasO",lastName:"Ahmad")     

    }


    @Test
    void testMinSize() {                
        assertTrue student.validate() // I guess this should return true but It returns false

    }

}

What is going wrong with that? How could I solve it?

Thanks,

I was doing something wrong this code:

if(!similarUser || obj.id == similarUser.id)

should be if(similarUser && obj.id == similarUser.id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM