写单元测试用于保存模型

时间:2012-06-26 08:16:21

标签: grails groovy grails-2.0

我是初学者...并且学习编写单元测试用例

我有2个域名

class Employee {

    String name
    String department

    static hasOne =[address: Address]   


    public String toString() {
        name
    }
}

class Address {

    String line1
    String line2

    Employee employee

    static constraints = {
    }
}

所以这是我的AddressControllerTest.groovy

 void testSave() {

        def address = new Address(line1: "Kaser Road", line2: "Bridage Town")
        .addToEmployee(new Employee(name: "monda", department:"IT")).save()

        controller.save()

        assert model.addressInstance != null
}

提供错误报告

No signature of method: trip.side.Address.addToEmployee() is applicable for argument types: (trip.side.Employee) values: [monda] Possible solutions: setEmployee(trip.side.Employee), getEmployee()
groovy.lang.MissingMethodException: No signature of method: trip.side.Address.addToEmployee() is applicable for argument types: (trip.side.Employee) values: [monda]
Possible solutions: setEmployee(trip.side.Employee), getEmployee()
    at trip.side.AddressControllerTests.testSave(AddressControllerTests.groovy:41)

任何人都可以建议我这样做的正确方法。

2 个答案:

答案 0 :(得分:2)

你需要告诉Grails,你要模拟哪些域类,所以使用:

mockDomain( Employee )
mockDomain( Address )

这与Grails 1.x有关,版本2.x使用注释:

@Mock( [ Employee, Address ] )

答案 1 :(得分:1)

虽然你仍然需要像Tom所说的那样进行模拟,但是你错误地使用了addTo* - 这正是错误信息告诉你的。 addTo*用于一对多和多对多关系,而不是一对一关系。您可以按照设置域名的方式执行此类操作:

def employee = new Employee(name: "monda", department:"IT", address: new Address(line1: "Kaser Road", line2: "Bridage Town")).save()