返回介绍

第九章 测试与调试

发布于 2025-02-26 23:37:53 字数 1827 浏览 0 评论 0 收藏 0

第九章 测试与调试

本章,我们将讨论以下话题:

  • Test-driven development
  • Dos and don'ts of writing tests
  • Mocking
  • Debugging
  • Logging

每个程序员都至少考虑过跳过编写测试。Django 中默认的 app 布局拥有一个包含注释的 tests.py 模块。它也是测试所需的一个提示器。不过,我们经常希望跳过它。

Django 中写测试和写代码很相似。实际上,它就是代码。因此,编写测试的过程看起来像是编写了两次(或者更多次)代码。有时候,我们承受了太多的压力,当我们花了很多时间尝试着去让代码正常工作时,虽然这样做看上去很荒唐。

However, eventually, it is pointless to skip tests if you ever want anyone else to use your code. Imagine that you invented an electric razor and tried to sell it to your friend saying that it worked well for you, but you haven't tested it properly. Being a good friend of yours he or she might agree, but imagine the horror if you told this to a stranger.

为什么要写测试

软件中的测试是为了检查软件本身是否按照人们所期望的那样正常运行。假如不对软件进行测试,你或许自认为自己写的代码可以正常运行,不过你也没有办法证明软件可以正常运行。

此外,重要的是要记得在 Python 中省略掉单元测试是比较危险的,因为 Python 存在自然——鸭子类型。跟 Haskell 这样的语言不同,类型检查在编译时并不能够严格地强制执行。单元测试在运行时得到执行(虽然是独立执行),这也是 Python 开发的基础。

编写测试是你会体会到什么是谦逊。测试会指出你的错误,而且你也得到了一个提前修正错误到机会。实际上,是有一些人愿意在编写代码之前去写测试到。

以测试驱动的开发

Test-driven development (TDD) is a for of software developent where you first write the test, run the test which would fail first, and then write the iniu code needed to make the test pass. This might sound counter-intuitive. Why do we need to write tests when we know that we have not written any code and we are certain that it will fail because of that?

However, look again. We do eventually write the code that erely satisfies these tests. This eans that these tests are not ordinary tests, they are ore like specifications. They tell you what to expect. These tests or specifications will directly coe fro your client's user stories. You are writing just enough code to ake it work.

The process of test

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文