I am developing a web app who does some work, pack the data in a file and gives you back that file (Content-Type: application/force-download
). Right now I am implementing some integration tests, where I ask for data and web app gives me back the file. Web app behaves correctly when test downloads expected data. I read this and I found it very inspiring but is that response valid when you build the file you want to download?
问题:
回答1:
There are several approaches you can take. In order from best to worst (YMMV):
Check the output semantically. For example, in case of JSON, check that it can be parsed, and expected keys and values are present. In case of an image, check that it can be parsed and has the right format.
Pro: You're only testing what you actually care about. Test failures can point at a specific problem.
Con: Takes more work.
Compare the file directly, byte by byte. The "golden master" approach. If the file is bigger that a few lines, or it's a binary file, I would put it on disk and have the integration test load it. This will also let you view/edit it in an external program more easily.
Pro: It's easy to see what the expected file looks like.
Con: Can be brittle in case of irrelevant changes. For example, the order of keys in a JSON object should not matter. Worse, if you're generating a PNG image, the time of creation could be embedded into the file so your test would fail every time.
Compare the file hash. I would view this as a last resort.
Pro: You don't need to store the entire file in your integration test, which is only nice if it's really big.
Con: A test failure tells you nothing. Even the hash embedded in your integration test tells you nothing. This is just a "change detector" test.