1

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

我有 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)

谁能建议我正确的做法。

4

2 回答 2

2

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

mockDomain( Employee )
mockDomain( Address )

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

@Mock( [ Employee, Address ] )
于 2012-06-26T08:39:23.437 回答
1

虽然您仍然需要像汤姆所说的那样进行模拟,但您使用addTo*不正确 - 这正是错误消息告诉您的内容。 addTo*用于一对多和多对多关系,而不是一对一关系。您可以按照设置域的方式执行以下操作:

def employee = new Employee(name: "monda", department:"IT", address: new Address(line1: "Kaser Road", line2: "Bridage Town")).save()
于 2012-06-26T22:29:56.493 回答