如何在类代码之前编写单元测试?

发布于 2024-09-02 21:26:10 字数 68 浏览 2 评论 0原文

我正在努力养成在实际上课之前编写单元测试的习惯。堆栈溢出社区可以为我提供哪些指示以及任何有用的资源。

谢谢

I am trying to get into the habit of writing a unit test before the actual class. What are some pointers the stack overflow community can give me along with any useful resources.

Thank You

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

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

发布评论

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

评论(4

你是我的挚爱i 2024-09-09 21:26:10

首先编写测试背后的想法是,在编写代码之前您就知道代码将要做什么。因此,您可以列出您希望它执行的操作以及您希望如何使用每个功能。然后,为每个功能编写一个测试(可以随意编写多个功能,或者测试对象的功能需要多少次。)

现在,您的类有了框架。您的第一个目标应该是通过添加类中使用的所有方法来编译测试。然后通过正确实施方法使测试通过。

Boom - 测试驱动开发将出现在您的简历中! :-)

The idea behind writing the test first is that you know what the code is going to do before you write it. So, you make a list of what you want it to do, and how you want each feature to be used. Then, you write a test for each feature (feel free to write more than one, or how ever many it takes to test the functionality of the object.)

Now, you have your framework for your class. Your first goal should be to make the test compile by adding all the methods used in the class. Then make the test pass by implementing the methods correctly.

Boom - Test Driven Development goes on your resume! :-)

合约呢 2024-09-09 21:26:10

这是一个很好的起点。它包含关于 TDD 的非常好的入门知识,以及指向其他资源的完整链接列表:

http:// /www.agiledata.org/essays/tdd.html

Here is a pretty good place to start. It contains a very good primer on TDD, with a comprehensive list of links to additional resources:

http://www.agiledata.org/essays/tdd.html

⊕婉儿 2024-09-09 21:26:10

我只有一个建议:

考虑一个方法应该做什么以及它应该如何表现,而不是如何编码。

这将允许您在不编写任何代码(甚至就此而言进行计划)的情况下规划单元测试。

I have but one pointer:

Think about what a method should do and how it should behave, not how you're going to code it.

That will allow you to plan the Unit Tests without having any code written (or even planned out, for that matter).

睫毛上残留的泪 2024-09-09 21:26:10

我通常通过编写一组业务规则作为我的类或脚本的 PHPDocs 的一部分来完成 TDD(使用 PHPUnit)。我不编写代码,只编写业务规则(例如 Foo 将抛出异常,如果...等)。完成后,我开始编写解决每个业务规则的测试用例。我发现首先编写业务规则可以帮助我建立一些边界,而测试用例则可以塑造实际的代码。

I generally do my TDD (with PHPUnit) by authoring a set of business rules as part of the PHPDocs for my class or script. I don't write the code, just the business rules (e.g. Foo will throw an exception if..., etc.). After I have that in place I start writing test cases that address each business rule. I've found writing the business rules first helps me establish some boundaries and the test cases shape the actual code.

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