在单元测试中是否有模拟对象的替代方案?
它是一个 Java(使用 JUnit)企业 Web 应用程序,没有预先构建模拟对象,并且创建它们需要大量的时间(未估计)。是否有一种测试范例可以为我提供“一些”测试覆盖率,但不是全部覆盖率?
It's a Java (using JUnit) enterprise Web application with no mock objects pre-built, and it would require a vast amount of time not estimated to create them. Is there a testing paradigm that would give me "some" test coverage, but not total coverage?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您是否尝试过动态模拟框架,例如 EasyMock?它不需要您“创建”Mock 对象,因为您必须编写整个类 - 您可以在测试本身中指定所需的行为。
使用
UserService
查找有关用户的详细信息以便让某人登录的类的示例:Have you tried a dynamic mocking framework such as EasyMock? It does not require you to "create" a Mock object in that you would have to write the entire class - you specify the behavior you want within the test itself.
An example of a class that uses a
UserService
to find details about a User in order to log someone in:(1) 单元测试(和模拟)的替代方案包括集成测试(使用 dbUnit)和 FIT 测试。有关更多信息,在此处查看我的答案< /a>.
(2)mocking框架Mockito非常出色。您不必“预先构建”任何模拟。引入项目相对容易。
(1) Alternatives to unit-testing (and mocks) include integration testing (with dbUnit) and FIT testing. For more, see my answer here.
(2) The mocking framework Mockito is outstanding. You wouldn't have to "pre-build" any mocks. It is relatively easy to introduce into a project.
我会回应其他人对 EasyMock 的看法。但是,如果您有一个代码库,需要模拟静态方法调用、最终类或方法等内容,请给出 JMockit一看。
I would echo what others are saying about EasyMock. However, if you have a codebase where you need to mock things like static method calls, final classes or methods, etc., then give JMockit a look.
好吧,获得高水平代码覆盖率的一种简单(如果不是最简单的)方法是遵循测试驱动开发 (TDD),以测试为先编写代码。现在代码已经存在,如果没有单元测试,它可以被视为遗留代码。
您可以在应用程序外部编写端到端测试,这些测试不是单元测试,但可以在不诉诸任何类型的模拟的情况下编写它们。或者,您可以编写跨越多个类的单元测试,并且仅模拟妨碍单元测试的类。
Well, one easy, if not the easiest, way to get an high level of code coverage is to write the code test-first, following Test-Driven Development (TDD). Now that the code exists, without unit tests, it can be deemed as legacy code.
You could either write end-to-end test, external to your application, those won't be unit tests, but they can be written without resorting to any kind of mock. Or you could write unit tests that span over multiple classes, and only mock the classes that gets in the way of your unit tests.
您是否有真实世界的数据可以导入到您的测试台中以用作您的“模拟对象”,这会很快
Do you have real world data you can import into your testbed to use as your 'mock objects' that would be quick
我认为相反的情况是很难的——找到一种可以提供全面覆盖的测试方法(如果在大多数情况下可能的话)。
I think the opposite is hard - to find a testing methodology that gives you total coverage, if at all possible in most cases.
您应该尝试一下EasyMock。
You should give EasyMock a try.