Django 测试休息框架 : APIRequestFactory vs APIClient

标签 django rest unit-testing django-rest-framework

作为测试新手,我希望在 Django (Django-rest-framework) 中测试我的 API。

我正在为我的 View 设置测试,即我的 API 端点。现在查看文档,我可以使用 APIRequestFactory 或 APIClient。两者似乎都在做同样的事情。

这两者之间有什么区别,为什么/什么时候我应该使用一个或另一个?

最佳答案

如果你看 tools and helpers for testing "standard" views in Django你会发现一些非常相似的东西, TestClient 和一个 RequestFactory .

The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view. This means you can test a view function the same way as you would test any other function – as a black box, with exactly known inputs, testing for specific outputs.


TestClient允许您从浏览您网站的用户的角度与您的网站进行交互(...虽然测试 Javascript 是另一回事)。像这样测试您的网站时,很多事情都会发挥作用( session 、中间件、URL 路由等)。因此,这些通常是模拟与您的网站或 API 的真实世界交互的更多集成测试。

一个 RequestFactory允许您以非常孤立的方式测试您的 View 。您可以构建请求并测试您的 View ,而无需设置您的 url 或关心中间件中发生的事情等。
所以这更接近于典型的单元测试。

也就是说,这两种类型的测试都是有用的。为了大致了解您的 API 是否按预期工作,我可能会开始使用 APIClient 并在涉及更复杂的 View 时使用 RequestFactories。但正确的组合很大程度上取决于您的具体应用。

关于Django 测试休息框架 : APIRequestFactory vs APIClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32136787/

相关文章:

javascript - 使用 Jest 测试 Vue 失败,Jest 遇到意外标记,SyntaxError : Unexpected token import

unit-testing - 如何对使用类型提示的函数进行单元测试

python - 在没有互联网访问的情况下部署 Django 的简单方法?

python - 我无法使用 django 连接到数据库

api - 如何使用 grails 构建数据库抽象层/API/中间件项目,我的看法是否可行?

javascript - REST API 的日期格式

django - 我们可以在 django 的单个 html 模板中扩展多个 html 吗?如果是,那么如何?

python - django从查询集中访问m2m字段属性

java - 返回REST API的漂亮错误JSON

java - Mockito 测试错误。需要但未调用的异常