简体   繁体   English

在单元测试中创建 API 资源的最佳实践 - 数据库或 POST 端点?

[英]Best practice for creating an API resource in unit test - database or POST endpoint?

What is the best practice for creating resources while unit testing a GET endpoint in a REST API?在 REST API 中对 GET 端点进行单元测试时创建资源的最佳实践是什么?

Should I create them directly in the database:我应该直接在数据库中创建它们:

  def test_can_get_todos_list(self):

        todo1 = Todo(text='todo1', user_id=self.user.id)
        todo2 = Todo(text='todo2', user_id=self.user.id)

        db.session.add_all([todo1, todo2]) # creating expected response todos directly in the database
        db.session.commit()

        response = self.client.get('api/todos')
        result = [
            {'text': 'todo1', 'id': 1},
            {'text': 'todo2', 'id': 2},
        ]
        
        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, response.json)

or should I utilize another API endpoint (POST) that I built for creating resources of this type.或者我应该使用我为创建此类资源而构建的另一个 API 端点 (POST)。 So instead of doing:所以不要这样做:

db.session.add_all([todo1, todo2]) 
db.session.commit()

I could do something like this:我可以做这样的事情:

self.client.post(/api/todos, data='todos payload here')

When testing the API as an integration test - ie as a completely external test - use the API for every part of the test.在将 API 作为集成测试(即完全外部测试)进行测试时,对测试的每个部分都使用 API。 Having some parts use the API and some parts use the internal API will make the test more brittle (ie changes to either functionality might need updating the test).让某些部件使用 API 而某些部件使用内部 API 会使测试更加脆弱(即,对任一功能的更改可能需要更新测试)。

Instead the test should use the API of the same abstraction level of the functionality that the tests implement.相反,测试应该使用与测试实现的功能具有相同抽象级别的 API。 If you're using the external API, you should use the external API for any feature of the tests.如果您使用的是外部 API,您应该使用外部 API 进行测试的任何功能。 That will also allow you to run the tests externally from your own code, and they will serve as both documentation and examples of how to use the API.这也将允许您从自己的代码外部运行测试,它们将作为文档和如何使用 API 的示例。

Implementing the tests in this manner will also expose any shortcomings of the API;以这种方式实施测试也将暴露 API 的任何缺点; if you discover functionality that you can't implement through the API but is required for writing the test, then you've found a use case that isn't covered by your current API.如果您发现无法通过 API 实现但编写测试所需的功能,那么您找到了当前 API 未涵盖的用例。

Many frameworks also feature dedicated test clients that sets up the test environment for you, so that the requests doesn't have to actually set up a listening socket and run a http server.许多框架还具有为您设置测试环境的专用测试客户端,因此请求不必实际设置侦听套接字并运行 http 服务器。 This speeds up the tests when testing the external API.这在测试外部 API 时加快了测试速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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