Python-mock:如何测试是否调用了super()

geu*_*ujv 5 python unit-testing mocking

我有以下结构:

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'
Run Code Online (Sandbox Code Playgroud)

我想要做的是编写一个测试用例,测试如果self.test为true则调用super函数并调用类A的方法函数.

我怎么能做到这一点?我该怎么做?

高级问:当A类和B类在一个单独的模块中时,它们具有相同的名称.因此,不是类BI而是写:类A(module1.A):这会改变模拟吗?

Mal*_*ina 8

正如@MartijnPieters所指出的,测试超级调用通常是对实现细节的测试,而不是对合同的测试.尽管如此,测试特定的实现仍然是可取的 - 或者父类可能有一个需要调用super的合同.要测试super被调用,请使用@mgilson提到的模拟.答案详细说明:

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)
Run Code Online (Sandbox Code Playgroud)

您需要在补丁中指定完整的命名空间.例如,@mock.patch("module.submodule.A.method").这可以用于A中的任何方法,包括__init__; 语法完全一样.