¿Qué es un el mocking?
Es la acción de reemplazar partes de tu sistema por objetos que imitan el comportamiento de dicha parte.
class Calculator:
def sum(self, a, b):
return a + b
from unittest import TestCase
from main import Calculator
class TestCalculator(TestCase):
def setUp(self):
self.calc = Calculator()
def test_sum(self):
answer = self.calc.sum(2, 4)
self.assertEqual(answer, 6)
import time
class Calculator:
def sum(self, a, b):
time.sleep(10)
return a + b
from unittest import TestCase
from unittest.mock import patch
class TestCalculator(TestCase):
@patch('main.Calculator.sum', return_value=9)
def test_sum(self, sum):
self.assertEqual(sum(2,3), 9)
Otro ejemplo
import requests
class Blog:
def __init__(self, name):
self.name = name
def posts(self):
response = requests.get("https://jsonplaceholder.typicode.com/posts")
return response.json()
def __repr__(self):
return '<Blog: {}>'.format(self.name)
from unittest import TestCase
from unittest.mock import patch, Mock
class TestBlog(TestCase):
@patch('main.Blog')
def test_blog_posts(self):
blog = Mock()
blog.posts.return_value = [
{
'userId': 1,
'id': 1,
'title': 'Test Title',
'body': 'Body content'
}
]
response = blog.posts()
self.assertIsNotNone(response)
self.assertIsInstance(response[0], dict)