简体   繁体   English

服务类的Grails单元测试中的params数据绑定

[英]params data binding in Grails unit test of a service class

I have a service method that takes params as an input and creates a domain class passing in params for auto binding. 我有一个服务方法,将参数作为输入并创建一个传递参数以进行自动绑定的域类。 Testing of this is simple by specifying params as a map of key value pairs. 通过将params指定为键值对的映射,测试起来很简单。 However, I don't know how to simulate an array of associated objects in the params map. 但是,我不知道如何在参数映射中模拟关联对象的数组。

I observed client side sending in params in the following format: 我观察到客户端以以下格式发送参数:

["description":"abc",  "subTask[0].name": "first subtask name"]

How do I mock this type of params? 我该如何模拟这种类型的参数? Since this is not a controller test I can not use mockParams AFAIK. 由于这不是控制器测试,因此无法使用模拟Params AFAIK。

The answer turns out to be this: Since controller params map parsing is not available in a Service class you have to convert values and objects on your own. 答案是:由于服务类中不提供控制器参数映射解析,因此您必须自己转换值和对象。 So in my example I have to manually create an array of associated objects within the params map. 因此,在我的示例中,我必须在params映射中手动创建关联对象的数组。 Here is an example: 这是一个例子:

  def params = [ state: "Open", type: "Cable", 
            needByDate: new Date("Fri May 11 00:00:00 PDT 2012"),
            //"subTasks[0]":["name":"ABC"]  //no workie
            "subTasks": [new Task("name": "ABC")]
  ]
  mockDomain(Task.class)
  Task task= service.saveNewRequest(params)

Hope this helps somebody. 希望这对某人有帮助。

The params map in Grails does magic stuff with parameter names that contain dots, making them available in the controller as "sub-maps". Grails中的params映射使用包含点的参数名称来执行魔术操作,使它们在控制器中可用作“子映射”。 For example if you have parameters ab=1 and ac=2 you can ask for params.a and get a map [b:1, c:2] . 例如,如果您有参数ab = 1和ac = 2,则可以要求params.a并获得映射[b:1, c:2] So try something like this: 所以尝试这样的事情:

["description":"abc",  "subTask[0]":["name": "first subtask name"]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM