如何使用unittest正确编写测试? [英] How do I write tests correctly using unittest?
问题描述
我想弄清楚如何为我用Python编写的函数编写单元测试 - 这里是下面的代码:
I am trying to figure out how to write unit tests for functions that I have written in Python - here's the code written below:
def num_buses(n):
import math
""" (int) -> int
Precondition: n >= 0
Return the minimum number of buses required to transport n people.
Each bus can hold 50 people.
>>> num_buses(75)
2
"""
bus = int()
if(n>=0):
bus = int(math.ceil(n/50.0))
return bus
我正在尝试编写测试代码,但是他们给了我失败的结果 - 这是我开始的代码:
I am attempting to write test code but they are giving me fail results - here's code I started with:
import a1
import unittest
class TestNumBuses(unittest.TestCase):
""" Test class for function a1.num_buses. """
def test_numbuses_1(self):
actual = num_buses(75)
expected = 2
self.assertEqual(actual, expected)
# Add your test methods for a1.num_buses here.
if __name__ == '__main__':
unittest.main(exit=False)
当我按F5运行模块时 - 这就是我得到的 -
When I run the module by pressing F5 - this is what I get -
E
======================================================================
ERROR: test_numbuses_1 (__main__.TestNumBuses)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\1-blog-cacher\TestNumBuses.py", line 8, in test_numbuses_1
actual = num_buses(75)
NameError: global name 'num_buses' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.050s
FAILED (errors=1)
所以我的测试失败了 - 虽然它应该通过,因为乘客的数量是75,每辆公共汽车最多可以容纳50人 - 除此之外的任何事情都会导致数字的四舍五入。
So my test Failed - although it should pass since the number of passengers are 75 and each bus can hold a maximum of 50 people - anything more than that will result in a rounding up of the figures.
有谁能看到我如何让测试用例工作以及我在哪里编写测试代码出错?
Can anyone see how I can get the test cases to work and where my writing the test code went wrong?
推荐答案
在您的unittest文件中,您必须 import num_buses
。
In your unittest file you have to import num_buses
.
这可以解决您的问题,但如果您在 a1
中定义了 num_buses
,那么您必须执行 a1.num_buses
否则Python会认为 num_buses
是一个全局函数。
This fixes your immediate problem, but if you have defined num_buses
in a1
then you have to do a1.num_buses
otherwise Python will think that num_buses
is a global function.
import a1
import unittest
import num_buses
class TestNumBuses(unittest.TestCase):
""" Test class for function a1.num_buses. """
def test_numbuses_1(self):
actual = num_buses(75) #a1.num_buses(75) <-
expected = 2
self.assertEqual(actual, expected)
# Add your test methods for a1.num_buses here.
if __name__ == '__main__':
unittest.main(exit=False)
检查出来: Cyber-Dojo测试 - 只需按简历,然后在 test_untitled.py
按下TEST按钮。
Check this out: Cyber-Dojo Test - just press resume and then in test_untitled.py
press the TEST button.
这篇关于如何使用unittest正确编写测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!