有没有办法使用side_effect模拟请求响应?

0 投票
1 回答
18 浏览
提问于 2025-04-13 14:42

我想像在这篇帖子中提到的那样,使用side_effect作为一个迭代器。

不过我想模拟一些响应,当我在我的函数中尝试访问response.status_code时,出现了错误AttributeError: 'dict' object has no attribute 'status_code'

我该如何使用side_effect来模拟不同的get请求响应,比如说:

mock_method.side_effect = [{"status_code": 404}, {"status_code": 200}]

我也试着这样做:

mock_method.side_effect.status_code = [404, 200]

结果也出现了类似的错误:

AttributeError: 'NoneType' object has no attribute 'status_code'

请帮帮我,我头疼得厉害,真希望昨天就能完成单元测试。

1 个回答

0

其实解决这个问题很简单,我只是创建了一个叫 MockResponse 的类,然后把 side_effect 设置成了这些对象的一个数组。

class MockResponse:
    def __init__(self, status_code, content):
        self.status_code = status_code
        self.content = content
    def json(self):
        return self.content

mock_method.side_effect = [MockResponse(200, data="success"), 
                           MockResponse(404, data="not found")]

撰写回答