当我无法访问状态时如何测试对象?
我有一个工厂类,它根据接收到的参数创建一个对象。该参数是一个标识符,告诉它应该创建哪个对象。 它的第一步是使用数据访问层来提取对象的信息。 下一步是对数据进行一些清理/转换。 最后它创建所需的对象并返回它。
我想确保清理/转换步骤顺利,但它返回的对象不会暴露任何状态,所以我不确定如何轻松测试它。
数据访问层和数据库结构无法更改,因为它们必须使用遗留代码。
在使用对象后,我可以在系统中进一步测试它,但这会导致难以维护的大型测试。
我还考虑过公开对象的状态,或者将责任放在另一个类中并进行测试,但这两个选项似乎都在更改测试系统。
对测试类似内容的其他方法有什么想法吗?
I have a factory class that creates an object based on a parameter it receives. The parameter is an identifier that tells it which object it should create.
Its first step is to use the data access layer to pull information for the object.
Its next step is to do some cleansing / transformations on the data.
Finally it creates the required object and returns it.
I want to ensure that the cleansing / transformation step went OK but the object that it returns does not expose any state so I'm not sure how to test it easily.
The data access layer and the database structure can't change because they have to work with legacy code.
I could test it further on in the system after the object gets used but that would lead to big tests that are hard to maintain.
I've also thought of exposing the state of the object, or putting the responsibility in another class and testing that, but both those options seem like I'm changing the system for testing.
Any thoughts on other ways to test something like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在我看来,您似乎试图在单元测试中测试太多内容。
这是你的单位试图做太多事情的症状。
您正在尝试在这里做三件事。
为了解决这个问题,我将按照您的建议将这些职责中的每一个转移到它们自己的单元(类/方法)中。然后您可以单独测试每个单元。
您对此犹豫不决,因为您不想更改系统进行测试。然而,单元测试的优点是它可以突出设计中的缺陷。您不仅要更改系统以进行测试,还要对其进行改进并使其更加精细,从而更易于维护和重用。
It sounds to me like you are trying to test too much within a unit test.
This is a symptom of your Unit trying to do too much.
You are trying to do three things here.
To fix I would move each of these responsibility into their own units ( classes / methods ) as you have suggested. Then you can test each unit on its own.
You are hesitant to do this as you don't want to change the system for testing. However, the advantage of unit testing is that it highlights flaws in the design. Not only are you changing the system for testing, you are improving it and making it more granular and thus more maintainable and reusable.