简体   繁体   English

如何在TDD中实现倒数计时器类?

[英]How to implement countdown timer class in TDD?

I'm learning to do TDD in practice in small project. 我正在学习在小型项目中进行TDD的实践。 I want to create a countdown timer class, how to implement it in TDD(Red, Green, Refactor), and it has the delegate callback as well. 我想创建一个倒数计时器类,如何在TDD(Red,Green,Refactor)中实现它,并且它还具有委托回调。

I am not sure of your exact question, but I think you want to know how you can write tests first for your countdown timer? 我不确定您的确切问题,但我想您想知道如何为倒数计时器首先编写测试?

If so start with writing one of the primary tests, say Start, Stop, or Reset. 如果是这样,请首先编写主要测试之一,然后说“开始”,“停止”或“重置”。 These are your action events and will be the ones you invoke first (most likely). 这些是您的动作事件,将是您最先调用的事件(最有可能发生)。 Code these tests first and execute them. 首先对这些测试进行编码并执行。 They should be red because they can't actually run the countdown timer. 它们应为红色,因为它们实际上无法运行倒数计时器。

Then add dummy code to one of the functions in your countdown timer. 然后将虚拟代码添加到倒数计时器中的功能之一。 For instance, add the Start() function which starts the countdown timer. 例如,添加Start()函数以启动倒数计时器。 Leave the function empty for now. 现在将该功能留空。 The test should still be red 测试应该仍然是红色的

Now we need to add a way to get the current time remaining. 现在,我们需要添加一种方法来获取当前剩余时间。 Add a "Remaining" property where we can check the time remaining. 添加“剩余”属性,我们可以在其中检查剩余时间。 Update the test so that it captures this property, starts the timer and then checks the property again to see if it changed. 更新测试,使其捕获该属性,启动计时器,然后再次检查该属性以查看其是否更改。 The test should be red still since we have no code to change the property. 由于我们没有更改属性的代码,因此测试仍应为红色

Update the start method to kick off your countdown process and update the internals of your countdown timer. 更新启动方法以启动倒计时过程,并更新倒数计时器的内部。 Rerun your test now and it should be green since the value is changing. 现在重新运行测试,由于值正在更改,因此应为绿色

Now it's time to refactor . 现在该重构了 Look through your code and clean things up. 查看您的代码并清理。 Simplify where you can and then reexecute your tests. 简化您可以使用的位置,然后重新执行测试。 If all is good everything should be green and you can move on to your next test. 如果一切顺利,则所有内容应为绿色,然后您可以继续进行下一个测试。

Hope that helps. 希望有所帮助。

Generally I don't test things like that in unit tests. 通常,我不会在单元测试中测试类似的东西。 Instead, I'll keep that code as small as possible, and have it call the class that does the work with either the time I want it to be, the elapsed time, or just a general "Do work now" kind of message. 取而代之的是,我将代码保持得尽可能小,并让它调用可以完成工作的类,或者是我希望的时间,已用的时间,或者只是一般的“立即开始工作”之类的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM