Home > Net >  Why can't I patch a class from a different file for my unit test?
Why can't I patch a class from a different file for my unit test?

Time:04-24

I have a file called some.py:

from dataclasses import dataclass
from some_folder.some_reader import SomeReader

class SomeClass:
    def __init__(self, url):
        self.reader = SomeReader(url)

and some_reader.py:

class SomeReader:
    def read_path(self, url):
        return "read_path"

and some_test.py:

from unittest.mock importpatch
from some_folder.some import SomeClass

@patch("some_folder.some_reader.SomeReader")
def test_some_class(mock_some_reader):
    SomeClass("")

When I run some_test, it seems that the SomeReader instantiated is not a mock object, instead it is:

SomeReader
<class 'some_folder.some_reader.SomeReader'>

Everything seems to work fine if I put SomeReader in some.py.

CodePudding user response:

See Where to patch

some.py:

from some_folder.some_reader import SomeReader


class SomeClass:
    def __init__(self, url):
        self.reader = SomeReader(url)

some_folder/some_reader.py:

class SomeReader:
    def read_path(self, url):
        return "read_path"

test_some.py:

import unittest
from unittest.mock import patch
from some import SomeClass


class TestSome(unittest.TestCase):
    @patch("some.SomeReader")
    def test_some_class(self, mock_some_reader):
        some = SomeClass("")
        print(some.reader)

if __name__ == '__main__':
    unittest.main()

Test result:

<MagicMock name='SomeReader()' id='4520784368'>
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
  • Related