用 Python 编写单元测试:我该如何开始? [英] Writing unit tests in Python: How do I start?

查看:71
本文介绍了用 Python 编写单元测试:我该如何开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 Python 完成了我的第一个合适的项目,现在我的任务是为它编写测试.

I completed my first proper project in Python and now my task is to write tests for it.

因为这是我第一次做项目,所以这是我第一次为它编写测试.

Since this is the first time I did a project, this is the first time I would be writing tests for it.

问题是,如何开始?我真的一点儿都不知道.任何人都可以指点我一些文档/教程/链接/书籍,我可以用它来开始编写测试(我猜尤其是单元测试)

The question is, how do I start? I have absolutely no idea. Can anyone point me to some documentation/ tutorial/ link/ book that I can use to start with writing tests (and I guess unit testing in particular)

欢迎就此主题提出任何建议.

Any advice will be welcomed on this topic.

推荐答案

如果您刚开始使用单元测试,那么最简单的学习方法通​​常是最好的.在此基础上,我建议使用 py.test 而不是 默认unittest 模块.

If you're brand new to using unittests, the simplest approach to learn is often the best. On that basis along I recommend using py.test rather than the default unittest module.

考虑这两个例子,它们做同样的事情:

Consider these two examples, which do the same thing:

示例 1(单元测试):

Example 1 (unittest):

import unittest

class LearningCase(unittest.TestCase):
    def test_starting_out(self):
        self.assertEqual(1, 1)

def main():
    unittest.main()

if __name__ == "__main__":
    main()

示例 2(pytest):

Example 2 (pytest):

def test_starting_out():
    assert 1 == 1

假设两个文件都被命名为test_unittesting.py,我们如何运行测试?

Assuming that both files are named test_unittesting.py, how do we run the tests?

示例 1(单元测试):

Example 1 (unittest):

cd /path/to/dir/
python test_unittesting.py

示例 2(pytest):

Example 2 (pytest):

cd /path/to/dir/
py.test

这篇关于用 Python 编写单元测试:我该如何开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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