编写单元测试:我可以在 class 级别只导入一次我需要的所有模块,还是必须在每次测试中再次导入它们?
Writing unit tests: can I import all modules I need just once at class level, or do I have to import them again in each test?
我正在尝试使用 unittest
:
为某些代码编写单元测试
https://docs.python.org/3/library/unittest.html
假设我正在编写的每个测试都需要导入 math
、os
和 datetime
模块。现在我正在编写的每个测试中导入它们:
#...code for which I'm writing the unit tests...
import unittest
class TestMyCode(unittest.TestCase):
def test_method_1(self):
# unit test for method 1
import math
import os
import datetime
.
.
def test_method_2(self):
# unit test for method 2
import math
import os
import datetime
.
.
if __name__ == "__main__":
unittest.main()
为了避免代码重复,难道不能在 class 级别只导入一次吗?这个:
#...code for which I'm writing the unit tests...
import unittest
class TestMyCode(unittest.TestCase):
import math
import os
import datetime
def test_method_1(self):
# unit test for method 1
.
.
def test_method_2(self):
# unit test for method 2
.
.
if __name__ == "__main__":
unittest.main()
导致错误
NameError: name 'math' is not defined
所以这显然不是正确的方法。
EDIT 只是为了清楚起见,我正在为其编写单元测试的代码(实际上仅由两种方法组成)和(两个)单元测试在同一个模块中,我们称它为MyCode.py
。
鉴于您要删除的重复代码由导入组成,我完全同意 BrenBarn 的回复,因为您不需要多次导入一个模块。
对于在 class 中的每个测试之前或之后想要 运行 相同代码的一般情况,您应该使用 class [=12= 的 setUp() 和 tearDown() 方法].
我正在尝试使用 unittest
:
https://docs.python.org/3/library/unittest.html
假设我正在编写的每个测试都需要导入 math
、os
和 datetime
模块。现在我正在编写的每个测试中导入它们:
#...code for which I'm writing the unit tests...
import unittest
class TestMyCode(unittest.TestCase):
def test_method_1(self):
# unit test for method 1
import math
import os
import datetime
.
.
def test_method_2(self):
# unit test for method 2
import math
import os
import datetime
.
.
if __name__ == "__main__":
unittest.main()
为了避免代码重复,难道不能在 class 级别只导入一次吗?这个:
#...code for which I'm writing the unit tests...
import unittest
class TestMyCode(unittest.TestCase):
import math
import os
import datetime
def test_method_1(self):
# unit test for method 1
.
.
def test_method_2(self):
# unit test for method 2
.
.
if __name__ == "__main__":
unittest.main()
导致错误
NameError: name 'math' is not defined
所以这显然不是正确的方法。
EDIT 只是为了清楚起见,我正在为其编写单元测试的代码(实际上仅由两种方法组成)和(两个)单元测试在同一个模块中,我们称它为MyCode.py
。
鉴于您要删除的重复代码由导入组成,我完全同意 BrenBarn 的回复,因为您不需要多次导入一个模块。 对于在 class 中的每个测试之前或之后想要 运行 相同代码的一般情况,您应该使用 class [=12= 的 setUp() 和 tearDown() 方法].