Java Return 值的空手道自定义序列化程序

Karate Custom Serialiser for Java Return Value

假设我有一个 Java class 这样的:

package com.example;
public class PersonUtil {
    static class Person {
        LocalDate dob;
        String name;
        Person(LocalDate dob, String name) { this.dob = dob; this.name = name;}
    }

    public static Person person() {
        return new Person(LocalDate.now(), "bob");
    }
}

然后我有这样的 common.feature 文件:

@ignore
Feature:

Scenario:
    * def personUtil = Java.type('com.example.PersonUtil')

然后是这样的 test.feature 文件:

Feature: Create Person

Background:
  * def util = call read('common.feature')
  * print util.personUtil.person();

问题是特征文件中的 dob 字段看起来像下面的结构:

{"dob": {"year":2019, 
    "month":"MAY", 
    "monthValue":5, 
    "dayOfMonth":1, 
    "leapYear":false, 
    "dayOfWeek":"WEDNESDAY", 
    "dayOfYear":121, 
    "era": "CE", 
    "chronology": {
        "id":"ISO", 
         "calendarType":"iso8601"
        }}, 
 "name":"bob"}

但我希望它使用 DateFormatter,所以输出是

{"dob": "2019-05-1", "name":"bob"}

有没有办法在不创建另一个 DTO 并自己进行 LocalDate 格式化的情况下使用 Karate 执行此操作?

是的,试试这个:

* def mapper = function(x){ return { name: x.name, dob: x.dob.toString() } }
* def person = mapper(util.personUtil.person())
* print person

根据以上内容,您应该很容易弄清楚如何进行任何类型的转换。

@Peter Thomas,谢谢,这确实有效,但它让我想得更多,我最终做的是重用我的一个 ObjectMapper 实用程序将对象序列化为 JSON(并且 objectmapper 处理所有的类型转换)。然后我用该序列化函数包装调用以获取 Java 对象,并将结果转换回功能文件中的 json ,如下所示:

与以前相同,但使用了新的 serialise 助手`:

package com.example;
public class PersonUtil {
    static class Person {
        LocalDate dob;
        String name;
        Person(LocalDate dob, String name) { this.dob = dob; this.name = name;}
    }

    public static Person person() {
        return new Person(LocalDate.now(), "bob");
    }

    public static String serialise(Object o) throws JsonProcessingException {
        return ObjectMapperUtils.createObjectMapper().writeValueAsString(o);
    }
}

与之前类似,但现在使用 serialise 助手包装调用:

Feature: Create Person

Background:
  * def util = call read('common.feature')
  * json person = util.personUtil.serialise(util.personUtil.person());
  * print person

这样我就不需要为每种需要特殊转换的 Java 对象创建一个新的映射器。