如何处理 TDD 的重构阶段

发布于 2024-11-01 13:50:35 字数 241 浏览 6 评论 0原文

在 TDD 会话过程中,假设我编写了一个失败的测试,然后使其通过。我通过使用诸如提取类和移动方法之类的重构从原始单元中提取代码来进行重构。现在进一步假设我的原始测试不再涵盖提取的代码,因为原始代码现在模拟了其依赖项,这对于单元测试来说是正确的。

返回并对提取的代码进行改造测试是否合适?或者我在重构过程中是否犯了一个错误,导致了未经测试的代码?感觉就像我的代码库正在扩展,我必须重构,我正在对重构的代码进行大量测试。这感觉实在是太尴尬了。我重构错了吗?

In the course of a TDD session, suppose I write a failing test, and then make it pass. I refactor by extracting code out of the original Unit, using refactorings such as Extract Class and Move Method. Now further suppose that my original test no longer covers the extracted code because the original code now mocks out its dependencies, as is correct for a Unit test.

Is it proper to go back and retrofit tests onto the extracted code? Or did I make a mistake in how I ended up with untested code during a refactoring? It feels like as my codebase is scaling, and I have to refactor, I'm retrofitting a lot of tests onto refactored code. This feels really awkward. Am I refactoring wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青春如此纠结 2024-11-08 13:50:35

现在进一步假设我的原始测试不再涵盖提取的代码,因为原始代码现在模拟了其依赖项,这对于单元测试来说是正确的。

模拟依赖项通常是一件好事,但并非总是如此,而且我不会说模拟所有依赖项“对于单元测试来说是正确的”。

在 TDD 的重构步骤中,您应该更改生产代码中不影响测试通过的内容。而且您不应该同时更改测试。

您可能希望稍后修改您的测试,以便提取的代码独立于原始代码进行测试,并在原始测试中进行模拟。

Now further suppose that my original test no longer covers the extracted code because the original code now mocks out its dependencies, as is correct for a Unit test.

Mocking dependencies is frequently a good thing to do, but not always, and I wouldn't say it's "correct for a unit test" to mock all dependencies.

In the refactoring step of TDD, you should be changing things in the production code that don't affect the passing of the tests. And you shouldn't be changing the tests at the same time.

You might want to later modify your tests so that the extracted code is tested independently of the original code and is mocked in the original tests.

潜移默化 2024-11-08 13:50:35

这可能表明您的单元测试不够细粒度。就像,您已经编写了集成测试并使其通过,现在您正在实施单元测试。

或者,在重构之后,您可能尝试对不应该进行测试的内容进行测试,例如私有方法。无论如何,重构不应该改变你的代码覆盖率。

This can be an indication that your unit tests are not fine-grained enough. Like, you've written integration test, made it pass, and now you're putting unit tests in place.

Or maybe after refactoring you are trying to put tests on something you shouldn't, such as private methods. Refactoring shouldn't change your code coverage anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文