Bob*_*ski 5 python testing unit-testing mocking
我真的试图开始隔离我的单元测试,这样我就可以确定错误发生的位置,而不是在出现问题时让整个屏幕变为红色.除了初始化程序中的某些内容失败之外,它一直在所有实例中工作.
看看这些测试:
@setup_directory(test_path)
def test_filename(self):
flexmock(lib.utility.time).should_receive('timestamp_with_random').and_return(1234)
f = SomeFiles(self.test_path)
assert f.path == os.path.join(self.test_path, '1234.db')
@setup_directory(test_path)
def test_filename_with_suffix(self):
flexmock(lib.utility.time).should_receive('timestamp_with_random').and_return(1234)
f = SomeFiles(self.test_path, suffix='.txt')
assert f.path == os.path.join(self.test_path, '1234.txt')
Run Code Online (Sandbox Code Playgroud)
我正在嘲笑依赖方法,以便我正在测试的东西是完全孤立的.您注意到的是,需要为每个测试实例化该类.如果在初始化程序中引入了错误,则每个测试都会失败.
这是调用类初始化程序的违规构造函数:
SomeFiles(*args)
Run Code Online (Sandbox Code Playgroud)
有没有办法隔离或模拟初始化器或对象构造函数?
我不确定您正在使用什么测试包,但一般来说,您通常可以__init__()在实际尝试使用该类之前模拟该类的调用。就像是
def my_init_mock_fn(*args, **kwargs):
print 'mock_init'
SomeFiles.__init__ = my_init_mock_fn
SomeFiles()
Run Code Online (Sandbox Code Playgroud)
这可能不完全是您想要的,因为从此时开始,SomeFiles.__init__fn 将始终是模拟 fn,但是有一些实用程序(例如voidspace mock)提供了修补函数,允许您仅针对特定范围修补类。
from mock import patch
with patch.object(SomeFiles, '__init__', my_init_mock_fn):
SomeFiles()
..other various tests...
SomeFiles() #__init__ is reset to original __init__ fn
Run Code Online (Sandbox Code Playgroud)
我确信您使用的任何模拟包中都可能有类似的功能。
刚刚意识到您正在使用 Flexmock,这里有一个页面replace_with 。
| 归档时间: |
|
| 查看次数: |
182 次 |
| 最近记录: |