moh*_*666 4 python unit-testing mocking stubs mox
我有一个方法可以调用其他两个方法.
def main_method(self, query):
result = self.method_one(query)
count = self.method_two(result)
return count
def method_one(self, query):
#Do some stuff based on results.
#This method hits the database.
return result
def method_two(self, result):
#Do some stuff based on result.
#This method also hits the database.
return count
Run Code Online (Sandbox Code Playgroud)
我在单元测试方面经验不足,从未与Mocks和Stubs合作过.
我不太确定如何为我的第一个方法创建单元测试.由于method_one和method_two多次访问数据库并且它们非常昂贵,因此我决定使用mox创建模拟或存根以消除命中数据库的需要.
如果有经验的Mocks和Stubs的经验给我一些关于在我的案例中使用模拟和存根的提示,我将非常感激.
在担心测试之前main_method(),首先测试较小的方法.考虑method_one().为了讨论的目的,让我们说它存在于这样的类中:
class Foo(object):
def method_one(self, query):
# Big nasty query that hits the database really hard!!
return query.all()
Run Code Online (Sandbox Code Playgroud)
为了在不命中数据库的情况下测试该方法,我们需要一个知道如何响应该all()方法的对象.例如:
class MockQuery(object):
def all(self):
return [1,2]
Run Code Online (Sandbox Code Playgroud)
现在我们可以测试一下:
f = Foo()
q = MockQuery()
assert f.method_one(q) == [1,2]
Run Code Online (Sandbox Code Playgroud)
这是一个基本的例子.现实世界往往更复杂.为了值得编写测试的麻烦,你的模拟all()可能会做一些比返回常量更有趣的事情.沿着类似的路线,如果method_one()包含一堆其他逻辑,我们MockQuery可能需要更精细 - 也就是说,能够适当地响应更多方法.通常在尝试测试代码时,您会意识到您的原始设计负担过重:您可能需要重构method_one()为更小,更严格定义 - 因此更可测试 - 的部分.
以相同的逻辑层次结构中的一个步骤,你可以创建一个MockFoo类,知道如何在简化的回应方式method_one()和method_two().
| 归档时间: |
|
| 查看次数: |
1030 次 |
| 最近记录: |