简体   繁体   中英

unit testing the unique constraint on domain class

I'm using Grails 2.4.1 and having trouble understanding how to properly test a unique constraint on a domain class.

My domain class looks like: class Person {

    String name
    static constraints = {
        name( unique: true, blank: false )
    }
}

and my test:

@TestFor(Person)
@TestMixin(GrailsUnitTestMixin)
class PersonSpec extends Specification {

void "name should be unique"() {
    given:
    mockForConstraintsTests Person

    when:
    def one = new Person( name: 'john' )

    then:
    one.save()

    when:
    def two = new Person( name: 'john' )

    then:
    ! two.validate()
    two.errors.hasFieldErrors( 'name' )

}

The second instance is validating despite apparently violating the unique constraint. Can someone please explain what's going on here and how I should best correct it?

Thanks!

--john

I do not think it is the best approach to test the constraints by triggering them. Generally we want to test that our code is working and not that Grails is validating the constraints.

Why test the framework (ie Grails)? Hopefully the Grails people have done that already :-) (yes, there are situations were it makes sense to check the framework, but I don't think this is one).

So the only thing to test is that we have placed the correct constraints on the domain class:

@TestFor(Person)
class PersonSpec extends Specification {

    void "name should have unique/blank constraints"() {
        expect:
        Person.constraints.name.getAppliedConstraint('unique').parameter
        ! Person.constraints.name.getAppliedConstraint('blank').blank
    }
}

If it is worth writing that test is another question...

This is exactly kind of mistake I used to do as a beginner. Testing grails stuff whether it is working as expected or not. Testing framework related stuff not a good idea. It means then testing all constraints, predefined methods and even save(), update() etc. So it would mean testing grails framework again rather than developing your application.

Testing should generally consists of testing your business logic related stuff.

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