【发布时间】:2018-02-02 12:52:20
【问题描述】:
我不明白为什么我们在某些测试用例中需要mock,尤其是像下面这样:
main.py
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)
test.py
import main
from unittest import TestCase
from unittest.mock import patch
class TestBlog(TestCase):
@patch('main.Blog')
def test_blog_posts(self, MockBlog):
blog = MockBlog()
blog.posts.return_value = [
{
'userId': 1,
'id': 1,
'title': 'Test Title,
'body': 'Far out in the uncharted backwaters of the unfashionable end of the western spiral arm of the Galaxy\ lies a small unregarded yellow sun.'
}
]
response = blog.posts()
self.assertIsNotNone(response)
self.assertIsInstance(response[0], dict)
此代码来自this blog。
我很好奇的是,正如您在测试代码中看到的那样,测试代码集blog.posts.return_value 是一些理想的对象(dict)。
但是,我认为这种嘲笑是没有用的,因为这段代码只是测试用户在测试代码中设置return_value的正确程度,而不是真正的Blog ' 对象真正返回。
我的意思是,即使我在 main.py 中让真正的posts 函数返回1 或a,这个测试代码也会通过所有测试,因为用户设置了return_value 在测试代码中正确!
不明白为什么需要这种测试..
你们能解释一下吗?
【问题讨论】:
-
是的。这个测试没用。教训:不要相信你在博客中读到的一切。
标签: python django unit-testing mocking