Mock, My Hero for Unittesting

Let me introduce the hero…. “MOCK” to the rescue

So what is Mock exactly? In my personal opinion, mock or mocking is a concept of “mocking" something as a BlackBox that we gave this BlackBox an input and we don’t care how the BlackBox works, but we can expect the result or output, then we use the output for other businesses. well my opinion about mocking maybe not 100% accurate, but let me gave you an example.

How I implement mocking in my PPL Projects

In my projects cases, the cases might be similar to the example I gave before, but instead of just using Gmail, I am also using firebase services, which is consist of auth and firestore. so in my case, I have to create a new account into my firebase auth, then after that, I need to save some metadata about this account into firestore, after this process finish, I will send an email to this newly created user an email consist of their email and password that can be used for login. it’s cleary we need further authentication process into the firebase auth and firestore and also I have to programmatically login to gmail account so I can send an email. Well, if I am doing a unittest for this feature without mocking, I think it's almost impossible, and if it’s possible, we will get a side-effect which is spam data in our firebase auth and our firestore. so to test this, I am using mock. in my project I was using python with flask, so for the testing tools, I am using pytest and unittest library for mocking.

create_user() function implementation

Conclusion

even I did not talk too much about how to use unittest mock in python, but for me, the game-changer is when we find out the idea behind mock itself because unittest library is just a tool and the important thing is we know the concept of mocking. So when you find a dead end when you are writing a test for your code, I hope this article about what is mocking could make you resolved your problems

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store