【问题标题】:How to check if requests.get() is called in a method using unittest.mock如何检查是否在使用 unittest.mock 的方法中调用了 requests.get()
【发布时间】:2021-08-22 04:28:46
【问题描述】:

我很难理解 unittest.mock 文档和 SO 上的许多示例。

我有一个带有方法的类:

my_class.py

import requests

class MyClass:

   def do_stuff(do_it=True):
       if do_it:
          requests.get('https://someapi.com')

我想要一个单元测试来检查 do_stuff 是否尝试使用 unittest.mock 调用 api

我有一个测试(非常简单):

test_my_class.py

from django.test import TestCase

class TestMyClass(TestCase)

    def test_do_stuff_uses_api(self):
        MyClass().do_stuff()
        # How to assert that requests.get() method was called once?

【问题讨论】:

    标签: python python-mock


    【解决方案1】:

    签出包裹requests_mock

    https://requests-mock.readthedocs.io/en/latest/history.html#called

    from django.test import TestCase
    import requests_mock
    
    class TestMyClass(TestCase)
    
        def test_do_stuff_uses_api(self):
            with requests_mock.mock() as m:
                m.get('https://someapi.com', json={....})
                MyClass().do_stuff()
                history = m.request_history
                self.assertEqual(len(history), 1, "Should have been called once")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2014-02-02
      • 2021-05-12
      • 2016-09-16
      • 1970-01-01
      • 2014-11-23
      • 2017-01-21
      相关资源
      最近更新 更多