簡體   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