-1

My function uses a non-existent library:

from a.b import c
def func():
    d = c()

How do I mock c? So far I tried these methods, but not sure why it doesn't work:

mock_a = Mock(name="a")
mock_a.b = Mock(name="b")
mock_d = Mock(name="d")
mock_a.b.c = MagicMock(return_value=mock_d)
sys.modules["a"] = mock_a

and also tried

mock_ab = Mock(name="a.b")
mock_d = Mock(name="d")
mock_ab.c = MagicMock(return_value=mock_d)
sys.modules["a.b"] = mock_ab
JobHunter69
  • 1,706
  • 5
  • 25
  • 49

1 Answers1

0

I will do something like this.

Suppose my test are in a file tests.py and the file I want to test is demo.py. Both file are in the same directory.

demo.py

This file contains the c function I want to mock during unit test.

from a.b import c
def func():
    d = c()

test.py

In the test, I will mock the method like this

# import patch from mock package
def test_demo_file():
    with patch("demo.c") as c_mock:
         # do what ever you want to do with c_mock. c_mock should mock the method c in demo.py file.

Note: demo.c means the file are in the same directory. If the files were in different directory, then demo.c will the import path of the file, means, it will be similar to how you will import the file in your test file.

Faizan
  • 268
  • 2
  • 9