TDD 如何处理模拟对象的变化 [英] TDD how to handle a change in a mocked object

查看:25
本文介绍了TDD 如何处理模拟对象的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写单元测试时,对于单元与之交互的每个对象,我正在采取这些步骤(从我对 JBrains 的集成测试是一个骗局):

In writing unit tests, for each object that the unit interacts with, I am taking these steps (stolen from my understanding of JBrains' Integration Tests are a Scam):

  1. 在单元中编写测试以确保它向协作对象发送正确的调用和参数
  2. 在单元中编写一个测试,确保它处理来自协作对象的所有可能的响应.这些响应都是模拟的,因此该单元是单独测试的.
  3. 在协作对象中编写测试以确保它接受调用和参数.
  4. 编写测试以确保每个可能的响应都被发回.

当我决定重构一个在步骤 2 中模拟了响应的对象时,我的问题就出现了.如果我改变对象响应调用的方式,其他对象对该调用进行的测试都不会失败,因为它们已经所有都被嘲笑以匹配旧风格.你如何使模拟与他们模拟的对象保持同步?是否有最佳实践?还是我完全误解了事情并且做错了所有事情?

My question comes around when I decide to refactor an object that has responses mocked in step 2. If I change the way the object responds to a call, none of the tests that other objects have for that call will fail because they have all been mocked to match the old style. How do you keep mocks up to date with the objects they are mocking? Is there a best practice for this? Or have I completely misunderstood things and am doing it all wrong?

推荐答案

我就是这样做的.

假设我必须更改接口方法 foo() 的响应.我收集了在列表中存根 foo() 的所有协作测试.我收集方法 foo() 的所有契约测试,或者如果我没有契约测试,我会收集 foo() 的所有当前实现的所有测试在列表中.

Suppose I have to change the responses from interface method foo(). I gather all the collaboration tests that stub foo() in a list. I gather all the contract tests for method foo(), or if I don't have contract tests, I gather all the tests for all the current implementations of foo() in a list.

现在我创建一个版本控制分支,因为它会很混乱一段时间.

Now I create a version control branch, because it'll be messy for a while.

I @Ignore(JUnit 语言)或以其他方式禁用存根 foo() 的协作测试,并开始一个一个地重新实现和重新运行它们.我让他们都过去了.我可以在不涉及 foo() 的任何生产实现的情况下做到这一点.

I @Ignore (JUnit speak) or otherwise disable the collaboration tests that stub foo() and start re-implementing and re-running them one by one. I get them all passing. I can do this without touching any production implementation of foo().

现在我一一重新实现实现 foo() 的对象,其预期结果与存根的新返回值匹配.请记住:协作测试中的存根对应于合同测试中的预期结果.

Now I re-implement the objects that implement foo() one by one with expected results that match the new return values from the stubs. Remember: stubs in collaboration tests correspond to expected results in contract tests.

此时,所有协作测试现在都假设来自 foo() 的新响应,而契约测试/实现测试现在期待来自 foo() 的新响应,所以它应该一切正常.(TM)

At this point, all the collaboration tests now assume the new responses from foo() and the contract tests/implementation tests now expect the new responses from foo(), so It Should All Just Work.(TM)

现在整合你的分支并给自己倒一些酒.

Now integrate your branch and pour yourself some wine.

这篇关于TDD 如何处理模拟对象的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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