您如何使用 TDD 拆分班级? [英] How do you go about splitting a class with TDD?

查看:31
本文介绍了您如何使用 TDD 拆分班级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得自己在TDD方面还算熟练,甚至被公司认为是TDD专家",但还是有一些情况我觉得不知道如何正确处理,所以我想听取别人的意见.

I feel pretty skilled in TDD, and I'm even consired the "TDD expert" in my company, but nevertheless, there are some cases that I feel I don't know how to handle properly, so I would like to hear other's opinions.

我的问题如下:尽管一般来说 TDD 帮助我想到了一个类的核心职责,并将所有其他职责提取到依赖类,但有时我会在一段时间后意识到其中一个类具有多个职责,需要对其进行重构和拆分它分为2个班.这个结论通常是因为该类的测试开始变得复杂或重复.我可以很容易地进行重构以将这个类拆分为我想要的设计(我以小步骤进行,保持绿色条).我的问题是,我最终得到了相同的复杂和重复的测试,现在将两个类一起测试,而我想为每个类进行单独的测试.我能想到的唯一(或多或少安全)方式是对每个测试执行以下操作(在我完成生产代码的重构之后):

My problems is as follows: Even though in general TDD helps me think of the core responsibility of a class, and extract every other responsibility to dependent classes, there are cases that after some time I realize that one of the classes has multiple responsibilities and it needs to be refactored and split it into 2 classes. This conclusion often comes because the tests of that class start to become complicated or repetitive. I can pretty easily do refactoring to split this class to the design I want (and I do it in small steps, keeping on the green bar). My problem is that I end up with the same complicated and repetitive tests that now tests the 2 classes together, while I would like to have seperate tests for each class. The only (more-or-less safe) manner I could think of for doing that, is to do the following for each test (after I completed the refactoring of the production code):

  1. 复制测试用例
  2. 将测试的一个副本更改为使用模拟而不是第一类,并将测试的另一个副本更改为使用模拟而不是第二类.
  3. 然后,如果我发现其中一个副本已经存在相同的测试,我会删除它.

我认为有时可以执行以下操作:

I think that sometimes its possible to do the following:

  1. 从头开始创建 2 个类(当然使用 TDD)
  2. 更改旧测试以使用新类而不是旧类
  3. 删除旧类
  4. 删除旧测试

这两种技术看起来都非常麻烦且耗时,所以我想知道:真正的专家"是如何解决这个问题的?

Both of these techniques seems pretty cumbersome and time consuming, so I wonder: how do the "real experts" go about this issue?

推荐答案

如果没有实际示例,我无法确定我是否明白您的意思.但听起来您试图孤立地测试每个类(甚至可能是每个方法).

Without an actual example I can't be sure I know what exactly you mean. But it sounds like you try to test every class (and maybe even every method) in isolation.

当我想要/必须将一个类拆分为多个类时,我仍然倾向于将生成的类集合视为一个单元并作为一个整体进行测试.只有当它们停止构建一个功能整体并开始成为独立的单元时,我才会相互独立地测试它们.

When I get to a point where I want to/have to split a class into multiple classes, I tend to still view the resulting collection of classes as a unit and test it as a whole. Only when they stop building a functional whole and start to become independent units, I test them independently of each other.

这篇关于您如何使用 TDD 拆分班级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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