为 REST API 编写单元测试的最佳方法是什么? [英] What's the best way to write unit tests for a REST API?

查看:36
本文介绍了为 REST API 编写单元测试的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为 API 包装器编写单元测试时,我应该对 REST API 端点进行真正的调用,还是应该使用模拟成功和错误调用的 mocl 响应?

When writing unit tests for an API wrapper, should I be making real calls to the REST API endpoints or should I use mocl responses that simulate successful and erroneous calls?

推荐答案

单元测试 意味着只测试你的单元(API 包装器),没有别的.因此,不幸的是,您应该模拟整个 API.

Unit tests mean testing only your unit (API wrapper), nothing else. Thus, unfortunately, you should mock the entire API.

另一方面,这从来没有给我足够的信心,所以我选择了系统测试(也称为组件测试).在这种情况下,您应该针对现有 API 运行您的 API 包装器,可能是嵌入的并与您的测试一起开始.在集成测试(最终场景)中,您针对真实但最有可能的 API 测试实例(沙箱、开发环境)运行 API 包装器.

On the other hand this never really gives me enough confidence, so I go for system tests (also known as component tests). In that case you should run your API wrapper against existing API, maybe embedded and started along with your test. In integration test, the ultimate scenario, you run your API wrapper against real, but most likely test instance of the API (sandbox, dev environment).

在成熟的数据库测试领域:单元测试模拟整个 DAO 级别,组件测试针对内存数据库运行,而集成测试使用一些假数据连接到真实数据库.

In well established area of database testing: unit tests mock entire DAO level, component tests run against in-memory database while integration tests connect to real database with some fake data.

这篇关于为 REST API 编写单元测试的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆