创建新属性时测试 BeanUtils/测试应该失败

发布于 2024-12-09 23:17:34 字数 310 浏览 0 评论 0原文

我正在使用 BeanUtils 将一些 DTO 类映射到域类(反之亦然)。 (使用 BeanUtils 复制属性)

我想测试我的代码。如果有人在 DTO 或 Domain 类中创建额外的属性,我该如何编写会失败的测试。

我仍在努力的尝试是遍历 BeanUtils.getPropertyDescriptors(class) 并找到相应的 getter 方法,然后为每个类(DTO 和 Domain)测试相等性。

有什么想法吗?

由于项目依赖性限制,我宁愿不使用像 Dozer 这样的东西。我正在使用 spring 3 的 beanutils。

I'm using BeanUtils to map some DTO class to Domain classes (and vice/versa). (using BeanUtils copy properties)

I want to test my code. How do I write test that will fail if someone writes creates an extra property in either the DTO or Domain class.

My attempt which I'm still working on is to traverse BeanUtils.getPropertyDescriptors(class) and find the corresponding getter methods THEN for each class (DTO and Domain) test for equality.

Any thoughts?

Due to project dependency constraints I would rather not use something like Dozer. I am using spring 3's beanutils.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

指尖上的星空 2024-12-16 23:17:34

如果您只关心测试额外的属性,您的测试方法可能如下所示:

void assertSameProperties(Class class1, Class class2) {
    Set<String> properties = new HashSet<String>();
    for (PropertyDescriptor prop : BeanUtils.getPropertyDescriptors(class1)) {
        properties.add(prop.getName());
    }
    for (PropertyDescriptor prop : BeanUtils.getPropertyDescriptors(class2)) {
        if (!properties.remove(prop.getName()) {
            fail("Class " + class2.getName() + " has extra property " + prop.getName());
        }
    }
    if (!properties.isEmpty()) {
        fail("Class " + class1.getName() + " has extra properties");
    }

}

如果您关心测试映射本身,那么您的方法是为两个类中存在的每个属性调用 getter 并检查它们的结果是否相等应该有效。不过,请记住“类”属性,对于不同类的对象,其值肯定会有所不同。

If you're concerned just with testing for extra properties, your test method could look like this:

void assertSameProperties(Class class1, Class class2) {
    Set<String> properties = new HashSet<String>();
    for (PropertyDescriptor prop : BeanUtils.getPropertyDescriptors(class1)) {
        properties.add(prop.getName());
    }
    for (PropertyDescriptor prop : BeanUtils.getPropertyDescriptors(class2)) {
        if (!properties.remove(prop.getName()) {
            fail("Class " + class2.getName() + " has extra property " + prop.getName());
        }
    }
    if (!properties.isEmpty()) {
        fail("Class " + class1.getName() + " has extra properties");
    }

}

If you are concerned with testing the mapping itself, then your approach with calling getters for each property that exists in both classes and checking their results for equality should work. Remember about 'class' property, though, its value will certainly be different for objects of different classes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文