Unit tests and fixtures
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 th开发者_运维知识库ese 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?
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.
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
精彩评论