如何JUnit测试从文件解析的对象 [英] How to JUnit testing objects which are parsed from file

查看:124
本文介绍了如何JUnit测试从文件解析的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,它解析一些文件而不是处理这些文件。解析器经过了很好的测试,但我也必须测试处理部分。
问题是单元测试函数我需要来自解析器的大对象。我不想手动创建对象(这是太多的时间)。
我的目标是重构一些流程函数,因为某些函数做了很多事情并且使用了大型对象。

I'm working a program which is parsing some files and than process these files. The parser is well tested, but I have to test the processing part too. The problem is to unit test functions I need big objects which comes from the parser. I don't want to create manually objects(it's too much time). My goal is to refactor some process functions because some function do a lot of thing and working with huge objects.

语言是java,我使用JUnit。

The language is java, and I use JUnit.

我试图保存对象并加载到单元中测试,但这是唯一的方法吗?
有什么建议吗?

I tried to save objects and load in the unit test, but this is the only way? Any suggestions?

提前致谢,
Peter

Thanks in advance, Peter

推荐答案

您可以尝试模拟已解析的对象,仅定义所需的返回值对于处理代码调用的特定方法。如果对象创建很复杂和/或对象有许多外部依赖项,这很有用。

You may try to mock the parsed objects, defining only the needed return values for specific methods called by the processing code. This is useful if the object creation is complex and/or the object has many external dependencies.

其他选项是您列出的:直接从文件加载已解析的对象,或者在单元测试中手动创建它们。我通常更喜欢后一种选择,因为单元测试应尽可能自包含。请注意,手动创建可能很繁琐,但您只需编写一次该代码,然后您可以使用不同的参数重复所有单元测试。使用基于文件的方法时,您需要创建大量文件,这些文件可能在各种小位上有所不同,并且很快就会成为维护问题。例如。如果文件格式在下一个版本中发生了变化怎么办?您需要手动编辑所有测试文件。使用第一种方法时,您只需要在一个地方修改测试设置代码。

The other options are what you listed: load the parsed objects from files directly, or create them by hand in your unit tests. I usually prefer the latter option, because unit tests should be self- containing as much as possible. Note that the manual creation may be tedious, but you need to write that code only once, then you can reuse it with different parameters for all of your unit tests. While with the file based approach, you need to create loads of files which probably differ in various small bits, and they quickly become a maintenance headache. E.g. what if the file format changes in the next release? You need to manually edit all test files. While with first approach, you only need to modify the test setup code in one place.

这篇关于如何JUnit测试从文件解析的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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