行为与基于状态的测试 [英] Behavior vs. State Based Testing

查看:30
本文介绍了行为与基于状态的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题是宗教战争的一部分,但我有以下情况:我有一个对象,Responder,它在对象 Updater 上调用一个方法来响应不同的事件.我最近以这种方式分离了测试:Updater 方法本身的基于状态的测试,以及调用它的 Responder 的基于行为的测试.也就是说,我在 Responder 测试中模拟了 Updater,只是为了确保它被调用.

I know this question is part of a bit of a religious war, but I have the following situation: I have an object, Responder that calls a method on object Updaterin response to different events. I recently separated the testing in this way: state-based tests for the Updater method itself, and behavior-based tests for the Responder that calls it. That is, I mock the Updater in the Responder tests, just to ensure that it is called.

我是否仍然应该测试应该在 Responder 测试中更新的对象的状态而不是模拟 Updater?我喜欢我所做的,因为它需要的设置更少,而且似乎可以更好地隔离测试.但是,这似乎将 Responder 的实现和预期行为与 Updater 联系起来.是不是太脆了?这是一个简化的例子.

Should I still be testing the state of the objects that are supposed to be updated in the Responder tests and not mocking the Updater? I like what I have done because it requires less setup and seems to better isolate the tests. However, this seems to tie the implementation and expected behavior of Responder to Updater. Is that too brittle? This is a simplified example.

推荐答案

如果我没有正确理解你的问题,你真的需要至少两个级别的测试:

If I did understand your question correctly you really need at least two levels of testing:

  1. 单元测试,您尝试仅测试一个类并模拟所有依赖项(因此在您的情况下需要在此处模拟 Updater).这些测试可帮助您开发代码(尤其是在您使用 TDD 时),确保类的行为符合设计,甚至记录该类的行为方式.几乎每个类都应该有单元测试.然而,正如您所注意到的,即使您有 100% 的测试覆盖率,您也无法保证您的程序可以正常运行甚至启动!

  1. Unit tests, where you are trying to test only one class and mock all the dependencies (so in your case Updater needs to be mocked here). These tests help you develop the code (especially if you are using TDD), make sure the class behaves as designed and even document how this class is meant to behave. Pretty much every class should have unit tests. However, as you noticed even if you have 100% test coverage you have no guarantee that your program works or even starts up!

验收、集成和端到端测试 - 这些测试涵盖整个应用程序或大模块,并测试一切是否协同工作.通常,您不会在此级别使用模拟(不过,您可能会存根整个模块/Web 服务,具体取决于上下文).这些测试不必测试每一个实现细节(也不应该),因为这是由单元测试完成的.他们确保一切都正确接线并协同工作.在您的情况下,您不会在这里嘲笑更新程序.

Acceptance, integration and end-to-end tests - these tests cover either the whole application or big modules and test that everything works together. In general you don't use mocks at this level (you might stub a whole module/web service though, depending on the context). These tests don't have to test every single implementation detail (and shouldn't), because this is done by unit tests. They make sure that everything is correctly wired and working together. In your case you wouldn't mock Updater here.

总而言之,我认为您确实需要同时执行这两项操作才能正确测试您的应用程序.

So to sum up I think you really need to do both to have your application properly tested.

这篇关于行为与基于状态的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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