在python单元测试中模拟一个类和一个类方法 [英] Mock a class and a class method in python unit tests

查看:240
本文介绍了在python单元测试中模拟一个类和一个类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python的unittest.mock在Django应用中进行一些测试.我想检查是否调用了一个类,并且还检查了其实例上的方法.

例如,给出以下简化的示例代码:

# In project/app.py
def do_something():
    obj = MyClass(name='bob')
    return obj.my_method(num=10)

然后进行此测试以检查正在发生的情况:

# In tests/test_stuff.py
@patch('project.app.MyClass')
def test_it(self, my_class):
    do_something()
    my_class.assert_called_once_with(name='bob')
    my_class.my_method.assert_called_once_with(num=10)

测试成功说出my_class被调用,但说出my_class.my_method没有被调用.我知道我缺少什么-在模拟的类上模拟方法吗? -但是我不确定该如何或如何使它起作用.

解决方案

您的第二个模拟断言需要测试您是在实例而不是类本身上调用my_method.

像这样调用模拟对象,

my_class().my_method.assert_called_once_with(num=10)
        ^^

I'm using python's unittest.mock to do some testing in a Django app. I want to check that a class is called, and that a method on its instance is also called.

For example, given this simplified example code:

# In project/app.py
def do_something():
    obj = MyClass(name='bob')
    return obj.my_method(num=10)

And this test to check what's happening:

# In tests/test_stuff.py
@patch('project.app.MyClass')
def test_it(self, my_class):
    do_something()
    my_class.assert_called_once_with(name='bob')
    my_class.my_method.assert_called_once_with(num=10)

The test successfully says that my_class is called, but says my_class.my_method isn't called. I know I'm missing something - mocking a method on the mocked class? - but I'm not sure what or how to make it work.

解决方案

Your second mock assertion needs to test that you are calling my_method on the instance, not on the class itself.

Call the mock object like this,

my_class().my_method.assert_called_once_with(num=10)
        ^^

这篇关于在python单元测试中模拟一个类和一个类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆