单元测试和夹具
我们有很多单元测试来测试很多网页和 REST API 服务。
目前,当我们的测试运行时,它会实时从这些页面中提取数据,但这有时可能需要很长时间才能运行,而且感觉测试应该测试更多的代码——而不仅仅是依赖它们的启动和响应(如果这有意义的话)。 .)。
保存有效的 api 响应并在设置期间通过单元测试加载它是否是更好的做法?
想法?
We have a bunch of unit tests which test a lot of webpages and REST API services.
Currently when our tests run it pulls from these pages live but this can take ages to run sometimes, and it also feels like the tests should be testing more of our code - not just relying on them being up and responding (if that makes sense..).
Is it better practice to save a valid api response and with the unit tests load this in during setup?
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
听起来你试图一次测试太多是的。
您应该完全单独测试生成 Rest API 响应的代码(如果此代码在您的控制下)和使用它的代码。如果您不控制生成 API 的代码,您应该向使用它的代码提供虚假的、有效的 API 答案,并将它们用于您的测试。
依赖页面的启动和响应听起来更像是集成测试。如果您依赖外部 API,那么进行集成测试来验证 API 是否仍按您的预期运行总是很有趣的。
It sounds like you are trying to test too much at a time yes.
You should test the code generating the response for the Rest API (if this code is under your cotrole) and the code using it completely separately. If you don't control the code generating the API you should feed the code using it with fake, valid API answers and use them for your tests.
Relying on the pages being up and responding sounds a lot more like integration testing. If you are relying on an external API, it is always interesting to have integration test to validate that the API still behaves as you expect, though.
我更愿意使用测试/模拟数据源而不是实际的实时数据源。这将使您无需实际使用网络资源即可读取数据,并且会提供更好的性能(根据您的体系结构,切换您使用的数据源可能会或可能不容易)。
但同样重要的是,它可以让您处理返回的数据,并让您测试边缘情况、无效数据响应等。根据您的应用程序对数据的处理方式,这可能很重要。
I would much rather use a test/mock data source instead of the actual live one. That will let you read the data without actually using network resources and will give better performance (depending on your architecture it may or may not be easy to switch which data sources you use).
But equally important it will let you play around with the data you give back, and lets you test edge cases, invalid data response etc. Depending on what your application does with the data, that may be important.
我处理这个问题的方法是使用模拟。假设您有一个负责调用外部服务的类,以及一个使用这些结果的单独的类。您可以创建调用服务的类的模拟,然后仅返回您想要的任何特定结果。然后,您可以测试需要结果的类,而无需处理任何外部调用。
http://en.wikipedia.org/wiki/Mock_object
http://martinfowler.com/articles/mocksArentStubs.html
The way I would handle this is to use mocking. Lets assume that you have a class that is responsible for calling the external services, and a separate class that uses those results. You could create a mock of the class that calls the services, and just return any particular result you want. Then, you can test the class that needs the results without dealing with any external calls.
http://en.wikipedia.org/wiki/Mock_object
http://martinfowler.com/articles/mocksArentStubs.html