1

我正在从 Grails 学习 grails - Jason Rudolph 的入门书。我的域类看起来像这样:

class Race {

  String name;
  Date startDateTime
  String city
  String state
  Float distance
  Float cost
  Integer maxRunners = 10000

  static hasMany = [registrations: Registration]

  static constraints = {
    name(maxSize: 50, blank: false)
    startDateTime(validator: {
      return it > new Date()
    })
    city(maxSize: 30, blank: false)
    state(inList: ['GA', 'NC', 'SC', 'VA'], blank: false)
    distance(min: 3.1f, max: 100f)
    cost(min: 0f, max: 999.99f)
  }

  String toString() { "${this.name} : ${this.city}, ${this.state}" }
}

我想测试 startDateTime 字段的自定义验证。测试看起来像这样:

class RaceTests extends GrailsUnitTestCase {
  protected void setUp() {
    super.setUp()
  }

  protected void tearDown() {
    super.tearDown()
  }

  void testCustomDateValidation() {
    def race = new Race()
    race.startDateTime = null
    assertFalse(race.validate())
  }
}

测试看起来类似于我之前提到的书中的测试。但我越来越

groovy.lang.MissingMethodException: No signature of method: racetrack.Race.validate() is applicable for argument types: () values: []

我被卡住了,没有找到任何解决方案:/任何帮助将不胜感激。

4

2 回答 2

5

你错过了 mockForConstraintsTests() 调用。常见的模式是在 setUp() 中执行此操作

protected void setUp() {
  super.setUp()
  mockForConstraintsTests(Race)    
}

详情: http: //mrhaki.blogspot.com/2009/04/unit-testing-constraints-in-domain.html

于 2010-08-19T23:31:38.173 回答
3

You should not use unit tests or mocking to test domain classes. Grails does create a unit test for domain classes and this should be changed. Move the class to the same package and folder under test/integration and change the base class to GroovyTestCase and you'll have a proper test that runs with the in-memory database and tests persistence, not the mocking framework.

于 2010-08-20T02:58:03.760 回答