1

I am struggling to mock a method inside another method i.e Let's say I have 2 classes A, B as follows:

class A:
    def method_A(self):
        return "Hi"
class B:
    def method_B(self):
        instance_A = A()
        result = instance_A.method_A()
        print(result)

Here I want to mock method_A while testing method_B but can't find a way. Thanks in advance

unitSphere
  • 241
  • 3
  • 17

3 Answers3

3

I hope this is what you are looking for.

class A:
    def method_A(self):
        return "Hi"
class B:
    def method_B(self):
        instance_A = A()
        result = instance_A.method_A()
        return result

import mock

def mock_A(self):
    return 'Bye'


def test_method_B():
    with mock.patch.object(A, 'method_A', new=mock_A):
        result = B().method_B()
        assert result == 'Bye'
1

What exactly do you mean by mocking a method? If you mean why your code isn't doing anything that's because you need to call the method afterwards:-

B.method_B()

Maybe that helps somehow, if not could you explain the problem a lil'bit more.

0

Well in that case first you wanna import mock library by simply typing import mock

then you wanna create a function for 1) Mocking

def mocking_method_A(self):
return Some_value

2)Testing

def testing_method_B():
    with mock.patch.object(A, 'method_A', new=mocking_A):
        result = B().method_B()
        assert result == Some_value