I am currently trying to learn how to Unit Test with Python and was introduced to the concept of Mocking, I am a beginner Python developer hoping to learn the concepts of TDD alongside my development of Python skills. I am struggling to learn the concept of mocking a class with a given input from the user for Python unittest.mock documentation. If I could get an example of how I would mock a certain function, I would be really grateful. I will use the example found here: Example Question
class AgeCalculator(self):
def calculate_age(self):
age = input("What is your age?")
age = int(age)
print("Your age is:", age)
return age
def calculate_year(self, age)
current_year = time.strftime("%Y")
current_year = int(current_year)
calculated_date = (current_year - age) + 100
print("You will be 100 in", calculated_date)
return calculated_date
Please could somebody create my an example Unit Test using Mocking to automate the input for age so that it would return the year which the mock'ed age would be 100.
Thank you.
You can mock the buildins.input method in Python3.x, and using with statements to control the scope of mocking period.
import unittest.mock
def test_input_mocking():
with unittest.mock.patch('builtins.input', return_value=100):
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With