Cannot fix class created by test class using unittest

I am trying to fix a class created by a class that I am trying to test, but it does not work. I read various documents, but still have not found what I'm doing wrong. Here is the code snippet:

In tests/Test.py :

 from module.ClassToTest import ClassToTest class Test(object): @mock.patch('module.ClassToPatch.ClassToPatch', autospec = False) def setUp(self, my_class_mock): self.instance = my_class_mock.return_value self.instance.my_method.return_value = "def" self.class_to_test = ClassToTest() def test(self): val = self.class_to_test.instance.my_method() #Returns 'abc' instead of 'def' self.assertEqual(val, 'def') 

In module/ClassToPatch.py :

 class ClassToPatch(object): def __init__(self): pass def my_method(self): return "abc" 

In module/ClassToTest.py :

 from module.ClassToPatch import ClassToPatch class ClassToTest(object): def __init__: # Still instantiates the concrete class instead of the mock self.instance = ClassToPatch() 

I know that in this case I could easily add a dependency, but this is just an example. In addition, we use one class for each file policy, with a file named as a class, hence the strange import name.

+5
source share
1 answer

As Norbert notes, the fix is ​​to change the layout of the line from

 @mock.patch('module.ClassToPatch.ClassToPatch', autospec = False) 

to

 @mock.patch('module.ClassToTest.ClassToPatch', autospec = False) 

In accordance with the documents :

The patch () decorator / context manager simplifies the modeling of classes or objects in the module under test. The specified object will be replaced by the layout (or another object) during the test and will be restored after the test is completed.

You are testing the ClassToTest module, not the ClassToPatch module.

+1
source

Source: https://habr.com/ru/post/1243704/


All Articles