问题描述
我正在连接一个简单的,如果是惯用的外部服务.
I'm connecting to a simple, if idiosyncractic, external service.
我认为我的单元测试不应该依赖于该外部服务的可用性或实现,因此我打算对其进行模拟.
I believe that my unit tests should not depend on the availability or implementation of that external service, so I intend to mock it out.
我需要模拟来接受并返回现实的消息和响应-否则我的测试将无法代表真实的事务状态.例如,它必须引发正确的错误-并且它至少有7种不同的方式可能会失败(在您和我之间,这不是一个设计得很好的外部服务).因此,最低限度我必须拥有消息/响应对的哈希值.
I need the mock to accept and return realistic messages and responses - otherwise my tests won't represent real states of affairs. For example, it has to throw the right kind of errors - and there are at least 7 different ways it can fail (between you and me it's not a very well designed external service). Therefore, at a bare minimum I have to have a hash of message/response pairs.
因此,模拟并没有减少偶然性,而是将其重新引入了其他地方.实际上,俗话说,现在我遇到了两个问题:我必须确保哈希表中的内容正确地表示了外部服务的行为方式.但是,可以肯定的是,响应对象X对消息 m 给出的标准来源是X本身.还有什么是冒险和混乱的.
So instead of reducing contingency, mocking has reintroduced it somewhere else. In fact, as the saying goes, now I've got two problems: I've got to be sure that what's in my hash is a fair representation of how the external service behaves. But surely the canonical source of what response object X gives to message m is X itself. Anything else is risky and messy.
我转错了方向吗?如何消除这种明显的圆度?
Have I taken a wrong turn? How can I eliminate this apparent circularity?
编辑我已经根据大法官的有用评论澄清了我认为的问题.
EDIT I've clarified what I think the problem is in the light of Justice's helpful comments.
推荐答案
让我介绍一下,只是为了避免重复自己.
Let me refer you to my two answers at another question about unit testing just to avoid repeating myself, first.
在这种环境下,我认为模拟可以为您提供的功能是它严格指定您认为该外部接口的行为.这意味着您已经进行了受控测试(某些事情告诉我,外部服务经常更改.)因此,不仅可以使用已知的良好"响应序列来测试和调试代码,而且还具有记录在案的集合您期望的例子.
The thing I think that mocking gives you in this environment is that it's rigorously specifying what you think the behavior of that external interface is going to be. This means that you've got a controlled test (something tells me this external service changes every so often.) So, not only can you test and debug your code with a known "good" sequence of responses, but you have a documented set of examples of what you expect.
如果我处于那种情况下,并且取决于真实的服务,我很想为外部服务编写单元测试或模拟..这样,如果您在实际操作中发现错误,则可以(1)使用外部接口的模拟对代码运行测试,以及(2)根据您的期望对外部服务进行测试.
If I were in that situation, and depending on the real service, I'd be tempted to write a unit test or mock for the external service as well. That way, if you observe a fault in real operation, you can (1) run the test against your code using the mock for the external interface, and (2) test the external service against your expectations.
但是,关键是要拥有您真正有信心并且可以完全控制的东西.
The point, though, is to have something for which you have real confidence and which you completely control.
这篇关于模拟外部服务如何改善单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!