用于创建 stub /假对象的 Python 库

标签 python testing mocking stub

我正在寻找 python stub 库。可以用来在我的单元测试中创建假类/方法的东西..有没有一种简单的方法可以在 python 中实现它..

谢谢

PS:我不是在寻找模拟库,您可以在其中记录和重放期望。

Difference between mock and stubs

最佳答案

我们这样做。

class FakeSomethingOrOther( object ):
   def __init__( self ):
       self._count_me= 0
   def method_required_by_test( self ):
       return self.special_answer_required_by_test
   def count_this_method( self, *args, *kw ):
       self._count_me += 1

设置它们并不需要太多

class TestSomething( unittest.TestCase ):
    def setUp( self ):
        self.requiredSomething = FakeSomethingOrOther()
        self.requiredSomething.attribute_required_by_test= 12
        self.requiredSomething.special_answer_required_by_test = 32
        self.to_be_tested = ActualThing( self.requiredSomething )

由于您不需要复杂的静态检查类型声明,您所需要的只是一个具有正确方法的类。您可以简单地强制测试属性值。

这些东西真的非常容易写。您不需要很多支持或图书馆。

在其他语言(即 Java)中,很难编写能够通过静态编译时检查的程序。由于 Python 没有这个问题,因此为测试目的编写模拟或伪造实现是微不足道的。

关于用于创建 stub /假对象的 Python 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2436220/

相关文章:

python - django-taggit:使标签在管理员中不需要

python - cv2.imread() 在 Mac 和 Linux 上给出不同的结果

javascript - 测试异步运行时如何使用 sinon 沙箱?

c++ - 如何在 C/C++ 中创建 JNIEnv 模拟

python - random.choice 在 Python 2 和 3 上给出不同的结果

python - 在本地主机上运行 docker 项目,但没有任何反应

python - 当我运行脚本时,为什么 Spyder 要保存我的 *.py 文件?

reactjs - 使用 store Mocha 和 Enzyme 测试组件

unit-testing - 如何在 mockito/Junit 中调用模拟方法而不是真实方法

python - 在 python 中模拟一个类