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

查看:315
本文介绍了为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天全站免登陆