简体   繁体   中英

Python unit test : Why need `mock` in a test?

I can not understand why we need mock in some test cases, especially like below:

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 code is from this blog .

What I'm curious about is that as you can see in test code, test code set blog.posts.return_value as some desirable object( dict ).

But, I think this kind of mocking is useless because this code just test How well the user set the return_value correctly in the test code, not what the real Blog ' object really return .

What I mean is, even if I make real posts function return 1 or a in main.py , this test code would pass all the tests because the user set the return_value correctly in the test code!

Can not understand why this kind of test is needed..

Could you guys explain please?

The example in itself is useless. In fact it mocks the wrong thing. Mocking should be used to replace things like services/databases etc.

For example: mocking the requests.get would be totally fine: you already assume that the requests library works, so during the test you can just avoid to perform the HTTP call and simply return the page content. In this way you'd be testing the logic of the posts method, without taking account what requests does (even if in this case it is extremely simple).

Certainly it does not make sense to mock the class you are testing. You should mock its dependencies!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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