简体   繁体   中英

Mock calls to class constructor with different class

I have the following classes:

    class A(object):
      def __init__(self):
          self.inner_class = B()
      def foo():
          self.inner_class.bar()

    class B(object):
      def bar():
          return 'No'

    class C(object):
      def bar():
          return 'Yes'

I want to mock such that instead of calling the constructor of B it will get a C object.

@patch(...something....)
def test_get_yes(self):
    A().foo() # Expected output is 'Yes'

How can I do it?

I know I can write the following test but I prefer not to:

def test_get_yes(self):
    a = A()
    a.inner_class = C()
    a.foo() # Expected output is 'Yes'

The thing you need to mock is the entry for B in A.__init__.__globals__ .

Assuming a slightly different set of class definitions than appear in your question:

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

class B(object):
    def bar(self):
        return 'No'

class C(object):
    def bar(self):
        return 'Yes'

Then the following should work:

@patch.dict(A.__init__.__globals__, {'B': C})
def test_get_yes():
    print(A().foo())

test_get_yes()  # Outputs yes, not no

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM