python mock testing part 2
in first part we learn some basic idea about mock testing
here is more
### Mock Object
to start with mock object we import mock from std lib
`from unittest.mock import Mock`
then create an instance of Mock object
```
mock = Mock()
//
<Mock id='4483746128'>
```
what we see mock is a representation of instance of Mock class which id is a string
as we discussed earlier, Mock is handy and used when we have to test external dependency. we can test this with an dependency json
from unittest.mock import Mock
import json
data = json.dumps({"name": "Bob", "age": 20})
json = Mock()
print(dir(json))
newData = json.dumps({"name": "Bob", "age": 20})
print(newData)
first we import Json module as an external dependency, we dump a python dict into json and put in a variable called data.
here `dump` is a method in Json.
when we import external dependency, usually we are going to use it's property and method. here dumps is and example. in testing environment, we try to imitate real object behaviour as close as possible.
what we want is imitate or Mock, patch external dependency's d `dump` method
after that we are Mocking json. `json=Mock()` now json don't have dump method. if we print
`print(dir(json))` we can see result that there is no dump method
but as we are patching/Mocking Json module we want to test `dumps` method, we don't need to create dump method by ourself because there going to be lots of method in real senario. here Python mock is so flexible that we can use dump method in our mock json object, Mock will create method/property when we access them.
newData = json.dumps({"name": "Bob", "age": 20})
print(newData)
//result
<Mock name='mock.dumps()' id='4459296208'>
as we mocked json, which don't have dumps method but here we are accessing is, if there is no method in an object we may get any exception , but if we print we can get another mock object of Mock object.