Grails在测试-app失败

时间:2016-02-18 19:37:28

标签: grails testing

我有我的域类和我的groovy类进行单元测试

class Product {

    String product_code
    String store
    int price
    String notes
    //static hasOne = [description: Description]

    static constraints = {
    product_code blank:false, size: 1..15
    price blank:false, scale: 2
    store blank:false, size: 1..40
    notes blank:true , size: 1..150
    }   
}


import org.apache.jasper.compiler.Node.ParamsAction;
import grails.test.mixin.*
import org.junit.*
import org.pricer.model.Product;

/**
 * See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
 */


@TestFor(Product)
class ProductTests {
void testSomething() {
    if (Product.hasErrors()){
        fail "not pass"
    }else 
        assert "Pass"
    }
}

当我尝试运行test-app我的ProductTest.testSomething我得到

No signature of method: org.pricer.model.Product.hasErrors() is applicable for argument types: () values: []
Possible solutions: hasErrors(), getErrors(),
setErrors(org.springframework.validation.Errors), clearErrors(), hashCode()
groovy.lang.MissingMethodException: No signature of method: org.pricer.model.Product.hasErrors() is applicable for argument types: () values: []
Possible solutions: hasErrors(), getErrors(), setErrors(org.springframework.validation.Errors), clearErrors(), hashCode()
at
org.grails.datastore.gorm.GormStaticApi.methodMissing(GormStaticApi.groovy:97)
at org.pricer.ProductTests.testSomething(ProductTests.groovy:20)

2 个答案:

答案 0 :(得分:1)

您没有在测试中实例化域类产品。试试f.e。:

void testSomething() {
    def product = new Product()
    if (product.hasErrors()){
        //do something
    }
}

答案 1 :(得分:0)

hasErrors()是一种实例方法。当你调用Product.hasErrors()时,你正在调用一个类/静态方法,在这种情况下,它不存在。

所以,正如majkelo所说,你首先需要一个Product实例。但是,您还需要trigger domain class validation,以便在出现错误时,hasErrors()会报告错误。

def product = new Product(product_code: 'ABC', store: 'StackOverflow', price: 1000000)

product.validate() /* You can also call product.save() to validate. */

if(product.hasErrors()) {
    /* Do your thing */
}

捷径

您可以将验证和错误检查结合起来,如下所示:

if(product.validate()) {
    /* validation passed. */
} else {
   /* validation failed. */
}