单元测试REST API [英] Unit Testing REST API

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

问题描述

我在单元测试和模拟方面有一些经验.以我有限的经验,我将使用两者来测试服务层,例如,模拟(存根?)数据库以消除依赖关系,并专注于对业务逻辑进行单元测试.

I have some experience with unit testing and mocks. In my limited experience I would use the two to test a service layer, for example, mocking (stubbing?) out the database to eliminate dependencies and concentrate on unit testing the business logic.

现在,我正在创建一个包装API实现,该实现将使用RESTful Web服务.发回给我的json结果结构不可用,例如:Twitter.我只是在构建客户端以与其API交互.我不确定如何对json结果进行单元测试.现在,我只是使用静态json结构来模拟http请求的结果.这可以确保将json反序列化到我的pojos中是正确的,但是我担心API的更改.如果api结构发生变化怎么办?如果api当前今天返回"title",明天返回"groovy_title"怎么办?我的单元测试无法解决这个问题.

Now I'm creating a wrapper API implementation that will consume RESTful web services. The json result structure sent back to me is out of my hands, for example: Twitter. I'm simply building the client to interface with their api. I'm unsure how to go about unit testing the json result. Right now I'm just mocking the result of the http request with a static json structure. This ensures that the deserialzing of json to my pojos is correct, but I'm concerned about API changes. What if the api structure changes? What if the api currently returns "title" today and "groovy_title" tomorrow? My unit test wouldn't catch that.

不过,据我了解-单元测试应该是快速的.以前我会模拟数据库,而现在我正在模拟http,但是我实际上应该使用具体的http实现,以便立即得到有关api更改中断的通知吗?还是有更好的方法来解决这种情况?

From my understanding though - unit tests are supposed to be quick. Previously I would mock the db and now I'm mocking http, but should I actually be using the concrete http implementation so I'm notified immediately of a breaking api change? Or is there a better way to approach this situation?

推荐答案

我将继续做您正在做的事情,并模拟代码和外部API之间的接口.如您所指出的那样,这不会检测到外部API中的更改.

I would continue to do what you are doing and mock the interface between your code and the external API. As you point out, this will not detect changes in the external API.

您可以编写 integration 测试,这些测试实际上将转到外部服务器以测试API更改.我怀疑您已经将进行交互的代码分离到了自己的服务器/模块中,因此您可以从字面上ping外部API,而不会受到应用程序中多个抽象层的阻碍.

You could write integration tests that actually go to the external server to test for API changes. I suspect you have separated out the code that does the interaction into its own server/module, so you can literally ping the external API without being obstructed by more than 1 abstraction layer in your app.

请注意,您可以在不使用应用程序代码的情况下构建这些测试;即只是wget或curl并对结果进行一些分析...

Note, you could build these tests without using your app code; i.e. just wget or curl and do some analysis on the results...

与此有关的问题很多.离开我的头顶:

The issues with this are numerious; off the top of my head:

您需要网络连接
较慢
外部服务可能会暂时关闭-也就是说,故障可能意味着不同的事情.

You need a network connection
Slower
The external service could be down temporarily -- i.e. failure could mean different things.
etc.

这篇关于单元测试REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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