相关疑难解决方法(0)

模拟python类的任何实例上的方法

我想在生产代码中模拟某些类的任何实例上的方法,以便于测试.Python中有没有可以促进这个的库?

基本上,我想要执行以下操作,但在Python中(以下代码是Ruby,使用Mocha库):

  def test_stubbing_an_instance_method_on_all_instances_of_a_class
    Product.any_instance.stubs(:name).returns('stubbed_name')
    assert_equal 'stubbed_name', SomeClassThatUsesProduct.get_new_product_name
  end
Run Code Online (Sandbox Code Playgroud)

从上面要注意的重要一点是我需要在类级别上模拟它,因为我实际上需要在我正在测试的事物创建的实例上模拟方法.

使用案例:

我有一个类QueryMaker在一个实例上调用一个方法RemoteAPI.我想模拟出RemoteAPI.get_data_from_remote_server返回一些常量的方法.如何在测试中执行此操作,而无需在RemoteAPI代码中放置特殊情况以检查其运行的环境.

我想要的实例:

# a.py
class A(object):
    def foo(self):
        return "A's foo"

# b.py
from a import A

class B(object):
    def bar(self):
        x = A()
        return x.foo()

# test.py
from a import A
from b import B

def new_foo(self):
    return "New foo"

A.foo = new_foo

y = B()
if y.bar() == "New foo":
    print "Success!"
Run Code Online (Sandbox Code Playgroud)

python testing mocking

29
推荐指数
3
解决办法
3万
查看次数

标签 统计

mocking ×1

python ×1

testing ×1