用于创建存根/假对象的 Python 库

发布于 2024-08-25 03:43:10 字数 234 浏览 2 评论 0原文

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

谢谢

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

模拟和存根之间的区别

I am looking for python stubbing library. Something that could be used to create fake classes/methods in my unit tests.. Is there a simple way to achieve it in python..

Thanks

PS: I am not looking for mocking library where you would record and replay expectation.

Difference between mock and stubs

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一生独一 2024-09-01 03:43:10

我们这样做。

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 不存在这个问题,因此为了测试目的而编写模拟或伪造的实现是很简单的。

We do this.

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

It doesn't take much to set them up

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 )

Since you don't require complex statically checked type declarations, all you need is a class with the right methods. You can force test attribute values in trivially.

These things are really, really easy to write. You don't need a lot of support or libraries.

In other languages (i.e., Java) it's very hard to write something that will pass muster with static compile-time checking. Since Python doesn't have this problem, it's trivial to write mocks or fake implementations for testing purposes.

Saygoodbye 2024-09-01 03:43:10

Python 模拟程序 看起来不错。

Mocker实例用于命令录制和重放
对任意数量的模拟对象的期望。

Python mocker looks nice.

A Mocker instance is used to command recording and replaying of
expectations on any number of mock objects.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文