繁体   English   中英

Python单元测试:为什么需要在测试中使用“模拟”?

[英]Python unit test : Why need `mock` in a test?

我不明白为什么在某些测试案例中需要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)

此代码来自此博客

我很好奇的是,正如您在测试代码中看到的那样,测试代码将blog.posts.return_value设置为某些所需的对象( dict )。

但是,我认为这种模拟是无用的,因为此代码仅测试用户在测试代​​码中正确设置return_value ,而不是真正的Blog对象真正返回的东西

我的意思是,即使我使真正的posts函数在main.py中返回1a ,该测试代码也会通过所有测试,因为用户在测试代码中正确设置了return_value

无法理解为什么需要这种测试。

你们能解释一下吗?

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

例如:嘲讽requests.get将完全罚款:你已经假定requests库的工作原理,所以在测试过程中你可以直接避免执行HTTP调用和简单的返回页面内容。 这样,您将在不考虑requests情况下测试posts方法的逻辑(即使在这种情况下,这非常简单)。

当然,模拟正在测试的类没有任何意义。 您应该嘲笑其依赖项!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM