Junit中如何处理测试数据?
在TDD(测试驱动开发)开发过程中,如何处理测试数据? 假设一个场景,解析一个日志文件来获取需要的列。为了进行强测试,如何准备测试数据?我是否可以正确地将这些文件定位到测试类文件中?
In TDD(Test Driven Development) development process, how to deal with the test data?
Assumption that a scenario, parse a log file to get the needed column. For a strong test, How do I prepare the test data? And is it properly for me locate such files to the test class files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
例如,Maven 使用文件夹结构约定来处理测试数据:
如果您使用 Maven 进行构建,您需要将测试资源放置在正确的文件夹中,如果您使用不同的构建,您可能需要使用这种结构,因为它不仅仅是一个 Maven 约定,在我看来,它接近“最佳实践”。
Maven, for example, uses a convention for folder structures that takes care of test data:
If you use maven for building, you'll want to place the test resources in the right folder, if your building with something different, you may want to use this structure as it is more than just a maven convention, to my opinion it's close to 'best practise'.
另一种选择是模拟您的数据,消除对外部源的任何依赖。这样就可以轻松测试各种数据条件,而无需拥有多个外部测试数据实例。然后,我通常使用成熟的集成测试来进行轻量级冒烟测试。
Another option is to mock out your data, eliminating any dependency on external sources. This way it's easy to test various data conditions without having to have multiple instances of external test data. I then generally use full-fledged integration tests for lightweight smoke testing.
在测试中对它们进行硬编码,以便它们接近使用它们的测试,从而使测试更具可读性。
从真实的日志文件创建测试数据。写下要编写的测试清单,逐一解决它们,并在通过后将其勾掉。
Hard code them in the tests so that they are close to the tests that use them, making the test more readable.
Create the test data from a real log file. Write a list of the tests intended to be written, tackle them one by one and tick them off once they pass.
里面的测试对我有用。但
没有成功。
不知道为什么,但也许它对其他人有帮助。
inside the test worked for me. But
didn't worked.
Don't know why but maybe it helps some others.
当我的测试数据必须是外部文件时(我试图避免这种情况,但不能总是这样),我将其放入与我的项目同一级别的保留测试数据目录中,并使用 getClass()。 getClassLoader().getResourceAsStream(path) 来读取它。测试数据目录不是必需的,只是为了方便。但尽量避免需要这样做;正如 @philippe 指出的那样,在测试中硬编码这些值几乎总是更好,就在你可以看到它们的地方。
When my test data must be an external file - a situation I try to avoid, but can't always - I put it into a reserved test-data directory at the same level as my project, and use
getClass().getClassLoader().getResourceAsStream(path)
to read it. The test-data directory isn't a requirement, just a convenience. But try to avoid needing to do this; as @philippe points out, it's almost always nicer to have the values hard-coded in the tests, right where you can see them.