2016-06-01 2 views
0

Grails 2.5.4を使用していますが、ドメインオブジェクトで定義された制約に基づく検証が機能しないようです。与えられた:Grailsのドメイン検証が機能しない

class Pet { 

    String name 

    static constraints = { 
     name(nullable: false, blank: false) 
    } 
} 

私は、次のようなコードをテストする場合:私は、コンソール上の検証出力を見ることを期待

Pet p = new Pet() 
    if(!p.save()) { 
     p.errors.each { 
      println it 
     } 
    } 

。代わりに、私は保存()上で実行時例外を受け取ります。

Class 
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException 
Message 
Column 'name' cannot be null 

これは私が期待される動作ではありません。検証が成功しなかった場合、save()はMySQL挿入呼び出しを行わないはずです。誰が問題が何であるか知っていますか?

私はまた、次のようにテスト:

Pet e = new Pet() 
    e.validate() 
    println e.hasErrors() 

そして、私は間違っている偽の出力を取得します。

私はペットに名前を付けると挿入がうまく動作します。セットアップは大丈夫です。妥当性確認だけが機能していないようです。

+0

動作を示すサンプルアプリケーションを提供できる場合は、何が問題になっているのかを特定するのは簡単です。 –

+0

デフォルトでは、プロパティはnullではなく、空の文字列はデータバインディングによってヌルに変換されるため、 'name(nullable:false、blank:false) –

答えて

1

バージョンがGrailsの2.xのドメインクラスを認識しないようです。

5.0.8にアップグレードして問題を解決しました。

1

それは私には意味がありません。私は、constraintsという言葉の誤字を探します。

https://github.com/jeffbrown/validationstuffのプロジェクトは以下のドメインクラスが含まれています

// grails-app/domain/demp/Pet.groovy 
package demo 

class Pet { 
    String name 

    static constraints = { 
     name(nullable: false, blank: false) 
    } 
} 

次コントローラ:

// grails-app/controllers/demo/DemoController.groovy 
package demo 

class DemoController { 

    def index() { 
     def p = new Pet() 
     p.validate() 
     def hasErrors = p.hasErrors() 

     render "Has Errors? $hasErrors" 
    } 
} 

そして、次のテスト:

// test/unit/demo/DemoControllerSpec.groovy 
package demo 

import grails.test.mixin.TestFor 
import spock.lang.Specification 

@TestFor(DemoController) 
@Mock(Pet) 
class DemoControllerSpec extends Specification { 

    void "test validation"() { 
     when: 
     controller.index() 

     then: 
     response.text == 'Has Errors? true' 
    } 
} 

// test/unit/demo/PetSpec.groovy 
package demo 

import grails.test.mixin.TestFor 
import spock.lang.Specification 

@TestFor(Pet) 
class PetSpec extends Specification { 

    void "test constraints"() { 
     expect: 
     !new Pet().validate() 
    } 
} 

アプリは、以下のブートストラップが含まれています:

// grails-app/conf/BootStrap.groovy 
class BootStrap { 

    def init = { servletContext -> 
     def pet = new demo.Pet() 
     pet.validate() 

     println "Has Errors? ${pet.hasErrors()}" 
    } 
    def destroy = { 
    } 
} 

アプリケーションの起動時に:問題は、バージョン5.0.4

の休止プラグイン依存関係を持つことが判明

Has Errors? true