我正在使用python中的unittest来测试一个项目。该项目定义了供其他python开发人员进行子类化的类。然后,可以运行该项目并利用用户编写的子类。
我想要测试子类的方法是否被项目传递了正确的数据。我该怎么做呢?从测试类中调用unittest.TestCase.assert*
方法并不简单,测试类是项目的子类化。
我曾尝试将TestCase
对象设置为全局变量,并从子类方法中调用TestCase
对象的assert方法,但全局变量似乎不是从测试类方法的作用域中定义的。
示例
import unittest
import myproject
class TestProjectClass(unittest.TestCase):
def test_within_class_method(self):
myproject.run(config_file_pointing_to_ProjectClass) # Calls SomeUsersClass.project_method()
class SomeUsersClass(myproject.UserClassTemplate):
def project_method(self, data_passed_by_project):
#want to test data_passed_by_project in here
pass
发布于 2016-08-28 20:58:18
通过使用raise
将自定义异常向上传递到unittest.TestCase
,我能够使其正常工作。自定义异常可以与需要测试的任何数据打包在一起。我没有在这里展示它,但是test_helper.py
只是Exception
的一个基本子类。
import unittest
import myproject
from test_helper import PassItUpForTesting
class TestProjectClass(unittest.TestCase):
def test_within_class_method(self):
try:
# The following line calls SomeUsersClass.project_method()
myproject.run(config_file_pointing_to_ProjectClass)
except PassItUpForTesting as e:
# Test things using e.args[0] here
# Example test
self.assertEqual(e.args[0].some_attribute_of_the_data,
e.args[0].some_other_attribute_of_the_data)
class SomeUsersClass(myproject.UserClassTemplate):
def project_method(self, data_passed_by_project):
#want to test data_passed_by_project in here
raise PassItUpForTesting(data_passed_by_project)
(由于某些原因,在同一文件中定义自定义异常不起作用,因为在用户的类中创建的异常的实例没有被标识为自定义异常的实例。通过sys.exc_*
检查异常,发现异常类型是不同的。因此,我将异常放在另一个模块中,导入它,它就起作用了。)
发布于 2016-08-27 06:47:03
https://stackoverflow.com/questions/39178265
复制相似问题