Python单元测试:为什么在测试中需要“mock”?

Python单元测试:为什么在测试中需要“mock”?,python,django,unit-testing,mocking,Python,Django,Unit Testing,Mocking,我不明白为什么在一些测试用例中需要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.j

我不明白为什么在一些测试用例中需要
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)
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)
此代码来自

我好奇的是,正如您在测试代码中所看到的,测试代码集
blog.posts.return\u value
是一个理想的对象(
dict

但是,我认为这种模拟是无用的,因为这段代码只是测试用户在测试代码中正确设置
return\u值的程度,而不是真正的
Blog
'对象返回的内容

我的意思是,即使我在main.py中设置real
posts
函数return
1
a
,此测试代码也会通过所有测试,因为用户在测试代码中正确设置了
return\u值

我不明白为什么需要这种测试


你们能解释一下吗?

这个例子本身是没有用的。事实上,它嘲笑了错误的事情。模拟应该用来代替服务/数据库等

例如:模拟
请求.get
完全可以:您已经假设
请求
库可以工作,因此在测试期间,您可以避免执行HTTP调用,只返回页面内容。这样,您就可以测试
posts
方法的逻辑,而不考虑
请求的功能(即使在这种情况下非常简单)


当然,模仿您正在测试的类是没有意义的。你应该嘲笑它的依赖性

对。这个测试没用。教训:不要相信你在博客上读到的一切。你说“嘲笑你正在测试的类是没有意义的”。但是如果我想测试某个类的所有实例方法呢?在这种情况下,我不应该模拟类吗?不,因为这样你就替换了你想要测试的东西。@user3595632 UnitTests中的单元是一个类,而不是一个方法。面向对象编程的焦点是由类声明描述并由数据和行为组成的对象。因此,单元测试应该将对象作为一个整体进行测试。模拟允许您在没有依赖项的情况下测试给定对象。