测试 fasthttp 和 httptest

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

Testing fasthttp with httptest

问题

我想知道如何使用Go语言基础库中的httptest包来测试使用fasthttp编写的应用程序。

我找到了这篇指南,很好地解释了测试的过程,但问题是httptest不满足http.Handler接口,所以我不知道如何处理http.HandlerFunc,因为fasthttp使用了自己的fasthttp.ListenAndServe,与之不兼容。

有什么办法可以创建一个包装器,或者以其他方式对使用fasthttp编写的库进行端到端测试吗?

英文:

I am wondering how I can test an application that's written with fasthttp using the httptest package in the base library of Go.

I found this guide which explains the testing pretty well, but the issue is that httptest does not satisfy the http.Handler interface so I have no idea how to do the http.HandlerFunc since fasthttp uses it's own fasthttp.ListenAndServe that's incompatible.

Any ideas on how to create a wrapper, or how to otherwise test a fasthttp written library end to end?

答案1

得分: 5

有两种可能的方法。对于处理程序的单元测试并不可行,因为您需要创建一个RequestCtx并存根/模拟所有必要的字段。

相反,我会对您的fasthttp处理程序调用的代码进行单元测试。我会对实际处理程序进行端到端测试。

有一个in memory listener实现,您可以使用它来避免实际侦听TCP端口或Unix套接字。您将初始化服务器,但在此侦听器上提供服务,而不是在网络连接上。

然后,您将创建一个HTTP客户端,并像正常情况下一样调用相关方法,但使用此侦听器作为传输。

如果您存根/伪造处理程序交互的任何内容,那么您可以将其限制在内存中,没有外部依赖项,即像单元测试一样,但实际上进行了完整的系统测试。

英文:

There are two possible approaches. Unit testing a handler isn't really viable as you would need to create a RequestCtx and stub/mock all necessary fields.

Instead, I would unit test the code that your fasthttp handlers call out
to. I would do e2e testing of the actual handlers themselves.

There is an in memory listener implementation that you could use to avoid actually listening on a TCP port or Unix socket. You would initialise the server but serve on this listener instead of on a network connection.

You would then create a HTTP client and call the relevant methods as normal but use this listener as the transport.

If you stub/fake anything that your handlers interact with then you could make this in-memory only with no external dependencies, i.e. like a unit test but it will actually doing a full system test.

huangapple
  • 本文由 发表于 2017年7月25日 15:07:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/45296230.html
匿名

发表评论

匿名网友

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

确定