【问题标题】:How can I get rid of "no such property" when testing a class that accesses Item.constraints.xyz?在测试访问 Item.constraints.xyz 的类时,如何摆脱“没有这样的属性”?
【发布时间】:2011-05-24 16:36:32
【问题描述】:

单元测试中的以下星座返回:No such property: title for class: myproject.Item Possible solutions: title

ItemController.groovy

def add = { 
    [itemInstance: new Item(), titleMin: Item.constraints.title.size.min() ] 
}

ItemControllerSpec.groovy

mockDomain Item
def result = controller.add()

我怎样才能模拟出那个约束线?

注意:我只想让测试运行而不是因为那条线而失败。

【问题讨论】:

    标签: unit-testing grails groovy mocking spock


    【解决方案1】:

    通过metaClass。在setUp() 中,写如下内容: Item.metaClass.'static'.constraints = [ title: [ size: [ min: {5}, max: {30} ] ] ]

    【讨论】:

    • 在我的情况下失败了。但是,感谢您的提示,维克多,我能够提出以下解决方案:Item.metaClass.'static'.getConstraints = { [ title: [size:5..20] ] }
    【解决方案2】:

    如果您的测试类扩展了GrailUnitTestCase,请在测试执行前调用mockForConstraintsTests(Item)。如果您无法扩展此类,请尝试在测试执行前调用grails.test.MockUtils.prepareForConstraintsTests(Item)

    【讨论】:

    • 唐,两种变体都失败了,并出现了与我最初的帖子中描述的相同的错误消息。我还使用新生成的 ItemControllerTests.groovy 进行了尝试,除了 testSomething 之外别无其他。你自己有没有类似的情况,在哪里有效?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-07
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2016-08-28
    相关资源
    最近更新 更多