对象不变性的单元测试 [英] Unit testing for object immutability

查看:78
本文介绍了对象不变性的单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保给定的一组对象是不可变的。



我正在考虑以下内容:


  1. 检查每个字段是否为私人最终

  2. 检查课程是否为最终

  3. 检查可变成员

所以我想我的问题是:是3.可能吗?



<我可以递归地检查一个类的每个成员是否有其字段 private final ,但这还不够,因为一个类可以有一个名为的e方法getHaha(param)例如,它将给定的param添加到数组中。



所以有一种很好的方法来检查对象是否是不可变的或者甚至可能吗?



谢谢,

解决方案

如果你生成您的数据模型及其所有代码,您可以确保您创建的可能的数据值对象是不可变的,以满足您的需求。



您遇到的问题是迪菲租用不变形式。即使 String 也会使测试失败字符串,日期,方法是不可变的吗?您可以通过这种方式证明类是严格不可变的,但您可能最好不要生成数据模型。


I want to make sure that a given group of objects is immutable.

I was thinking about something along the lines of:

  1. check if every field is private final
  2. check if class is final
  3. check for mutable members

So I guess my question is: is 3. possible ?

I can check recursively whether every member of a class has its fields private final, but this is not enough since a class can have e method named getHaha(param) which adds the given param to an array for instance.

So is there a good way to check if an object is immutable or is it even possible ?

Thanks,

解决方案

If you generate your data model and all its code, you can ensure the possible Data Value objects you create will be immutable to meet your needs.

The problem you have is that there is different forms of immutability. Even String would fail your test Are String, Date, Method immutable? You can prove that a class is strictly immutable this way, but you are likely to be better off generating your data model.

这篇关于对象不变性的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆