Python模拟:如何测试是否调用了super() [英] Python-mock: how to test if super() was called

查看:107
本文介绍了Python模拟:如何测试是否调用了super()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

class A(Object):
    def method(self):
        return 'a'

class B(A):
   def __init__(self, test):
       self.test = test

   def method(self):
        if self.test:
           return super(A, self).method(self)
        else:
           return 'b'

我想做的是编写一个测试用例,用于测试self.test是否为true,然后调用超级函数,并调用A类的方法函数.

What I want to do is write a test-case which would test that if self.test is true then the super function was called and class A's method function was called.

我该如何实现?我该嘲笑什么?

How I can achieve this? What should I mock?

高级问:当A类和B类位于单独的模块中并且它们具有相同的名称时,该怎么办? 因此,我将代替类B编写:类A(module1.A): 会改变嘲笑吗?

Advanced Q: What about when Class A and B are in a separate module, and they have the same name. So instead of class B I would write: class A(module1.A): does that change the mocking?

推荐答案

@MartijnPieters 指出,正在测试所谓的超级通常是对实现细节的测试,而不是合同的测试.尽管如此,仍然可能需要测试特定的实现-否则父类可能具有要求调用super的合同.要测试是否调用了super,请使用模拟程序,如 @mgilson 所述.详细的答案:

As @MartijnPieters points out, testing that super is called is typically a test of an implementation detail, rather than a test of a contract. Nonetheless, testing the specific implementation may still be desirable -- or the parent class may have a contract requiring the call to super. To test that super is called, use a mock, as mentioned by @mgilson. The answer in detail:

import mock, unittest

class TestB(unittest.TestCase):

    @mock.patch("A.method")
    def test_super_method(self, mock_super):
        B(True).method()
        self.assertTrue(mock_super.called)

    @mock.patch("A.method")
    def test_super_method(self, mock_super):
        B(False).method()
        self.assertFalse(mock_super.called)

您需要在补丁中指定完整的名称空间.例如@mock.patch("module.submodule.A.method").可以对A中的任何方法(包括__init__)进行此操作.语法完全一样.

You'll need to specify the full namespace in the patch. E.g., @mock.patch("module.submodule.A.method"). This can be done for any method in A, including __init__; syntax is exactly the same.

这篇关于Python模拟:如何测试是否调用了super()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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