通过输出完整性检查进行单元测试 [英] unit test via output sanity checks

查看:32
本文介绍了通过输出完整性检查进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常看到将固定输入输入程序的测试,通常通过差异检查生成的输出与固定(预期)输出.如果差异被接受,则该代码被视为通过测试.

I have often seen tests where canned inputs are fed into a program, one checks the outputs generated against canned (expected) outputs usually via diff. If the diff is accepted, the code is deemed to pass the test.

问题:

1) 这是一个可接受的单元测试吗?

1) Is this an acceptable unit test?

2) 通常单元测试输入是从文件系统读入的并且很大xml 文件(也许它们代表一个非常大的系统).是否应该进行单元测试触摸文件系统?或者单元测试会动态创建一个小的输入并将其提供给要测试的代码?

2) Usually the unit test inputs are read in from the file system and are big xml files (maybe they represent a very large system). Are unit tests supposed to touch the file system? Or would a unit test create a small input on the fly and feed that to the code to be tested?

3) 如何重构现有代码以使其可进行单元测试?

3) How can one refactor existing code to be unit testable?

推荐答案

输出差异

如果您的要求是产生具有一定准确度的输出,那么这样的测试绝对没问题.由您做出最终决定 - 这个输出是否足够好?".

Output differences

If your requirement is to produce output with certain degree of accuracy, then such tests are absolutely fine. It's you who makes the final decision - "Is this output good enough, or not?".

您不希望您的测试通过依赖某些文件存在于某处来与文件系统对话,以便您的测试工作(例如,从配置文件中读取值).它与测试输入资源有点不同——您通常可以将它们嵌入到您的测试(或至少是测试项目)中,将它们视为代码库的一部分,最重要的是它们通常应该被加载before 测试执行.例如,在测试相当大的 XML 时,将它们存储为单独的文件是合理的,而不是代码文件中的字符串(有时可以这样做).

You don't want your tests to talk to file system in terms of relying on some files to exists somewhere in order for your tests to work (for example, reading values from configuration files). It's a bit different with tests input resources - you can usually embed them in your tests (or at least test project), treat them as part of codebase, and on top of that they usually should be loaded before test executes. For example, when testing rather large XMLs it's reasonable to have them stored as separete files, rather than strings in code files (which sometimes can be done instead).

重点是 - 您希望保持测试隔离和可重复.如果您可以通过在运行时加载文件来实现这一点 - 可能没问题.然而,将它们作为代码库/资源的一部分仍然比位于某处的标准系统文件更好.

Point is - you want to keep your tests isolated and repeatable. If you can achieve that with file being loaded at runtime - it's probably fine. However it's still better to have them as part of codebase/resources than standard system file lying somewhere.

这个问题相当广泛,但为了让您找到正确的方向 - 您想介绍更多 可靠 设计,分离 对象和分离职责.更好的设计将使测试更容易,最重要的是 - 可能.就像我说的,这是一个广泛而复杂的话题,整本书 致力于它.

This question is fairly broad, but to put you in the right direction - you want to introduce more solid design, decouple objects and separate responsibilities. Better design will make testing easier and, what's most important - possible. Like I said, it's broad and complex topic, with entire books dedicated to it.

这篇关于通过输出完整性检查进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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