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

发布于 2024-08-25 09:38:22 字数 68 浏览 4 评论 0原文

我正在小项目的实践中学习TDD。我想创建一个倒数计时器类,如何在 TDD(红色,绿色,重构)中实现它,并且它也有委托回调。

I'm learning to do TDD in practice in small project. 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.

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

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

发布评论

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

评论(2

对岸观火 2024-09-01 09:38:24

我不确定你的确切问题,但我想你想知道如何首先为倒计时器编写测试?

如果是这样,请从编写主要测试之一开始,例如启动、停止或重置。这些是您的操作事件,并且将是您首先调用的事件(最有可能)。首先对这些测试进行编码并执行它们。它们应该是红色,因为它们实际上无法运行倒计时器。

然后将虚拟代码添加到倒计时器中的函数之一。例如,添加启动倒计时器的 Start() 函数。暂时将该函数留空。测试应该仍然是红色

现在我们需要添加一种方法来获取当前剩余时间。添加“剩余”属性,我们可以在其中检查剩余时间。更新测试,以便捕获此属性,启动计时器,然后再次检查该属性以查看它是否发生更改。测试应该仍然是红色,因为我们没有代码来更改属性。

更新启动方法以启动倒计时过程并更新倒计时器的内部结构。现在重新运行您的测试,它应该是绿色,因为值正在变化。

现在是时候重构了。查看您的代码并清理内容。尽可能简化,然后重新执行测试。如果一切顺利,一切都应该是绿色,您可以继续进行下一个测试。

希望有帮助。

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. 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.

_失温 2024-09-01 09:38:24

一般来说,我不会在单元测试中测试类似的东西。相反,我将保持该代码尽可能小,并让它按照我想要的时间(经过的时间)或只是一般的“立即开始工作”类型的消息来调用执行工作的类。

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.

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