【问题标题】:Python unit test : Why need `mock` in a test?Python 单元测试:为什么在测试中需要“模拟”?
【发布时间】:2018-02-02 12:52:20
【问题描述】:

我不明白为什么我们在某些测试用例中需要mock,尤其是像下面这样:

ma​​in.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 ' 对象真正返回

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

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

你们能解释一下吗?

【问题讨论】:

  • 是的。这个测试没用。教训:不要相信你在博客中读到的一切。

标签: python django unit-testing mocking


【解决方案1】:

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

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

当然,模拟您正在测试的课程是没有意义的。你应该模拟它的依赖关系!

【讨论】:

  • 您说“模拟您正在测试的课程没有意义”。但是如果我想测试某个类的所有实例方法呢?在这种情况下,我不应该嘲笑这个班级吗?
  • 不,因为那样你正在替换你想要测试的东西。
  • @user3595632 unitests 中的单位是一个类,而不是单个方法。 Object Oriented Programming 的重点是objects,它们由类声明描述并由数据和行为组成。所以单元测试应该测试一个整体的对象。模拟允许您在没有依赖关系的情况下测试给定对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多