When to use httptest.Server and httptest.ResponseRecorder

huangapple go评论71阅读模式
英文:

When to use httptest.Server and httptest.ResponseRecorder

问题

标题中提到了 httptest.Server 和 httptest.ResponseRecorder,想知道何时使用它们。

在我看来,我也可以使用 httptest.Server 来测试处理程序是否返回正确的响应。我可以简单地启动一个带有处理程序实现的 httptest.Server,然后对响应的主体进行验证。

如果我理解错了,请纠正一下。我正在学习 Go 和 TDD。

英文:

As title, when to use httptest.Server and httptest.ResponseRecorder?

It seems to me that I can also test my handlers to return correct response using httptest.Server. I can simply start a httptest.Server given with my implementation of handlers, then do validations on the response's body.

Please correct if I'm wrong, I am learning Go + TDD

答案1

得分: 5

当你只想检查你的http.Handler是否按照预期工作时,你不需要使用httptest.Server。只需使用httptest.ResponseRecorder实例调用你的处理程序,并像示例中那样检查输出。

httptest.Server的可能用途很多,以下是我能想到的一些例子:

  • 如果你的代码依赖于一些外部服务和API,你可以使用测试服务器来模拟它们。(尽管我个人会将所有处理外部数据源的代码隔离,并通过接口使用它们,这样我就可以轻松地为我的测试创建虚拟对象。)

  • 如果你正在开发一个客户端-服务器应用程序,你可以在测试客户端时使用测试服务器来模拟服务器端的行为。

英文:

When you just want to check, if your http.Handler does what it should, you don't need to use httptest.Server. Just call your handler with an httptest.ResponseRecorder instance and check the output as in the example.

The possible uses of httptest.Server are numerous, so here are just a couple that come to my mind:

  • If your code depends on some external services and APIs, you can use a test server to emulate them. (Although I personally would isolate all code dealing with external data sources and then use them through interfaces, so that I could easily create fake objects for my tests.)

  • If you work on a client-server application, you can use a test server to emulate the server-side when testing the client-side.

huangapple
  • 本文由 发表于 2014年9月18日 19:50:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/25911878.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定