I’ve written a script that opens up a file, reads the content and does some operations and calculations and stores them in sets and dictionaries.
How would I write a unit test for such a thing? My questions specifically are:
- Would I test that the file opened?
- The file is huge (it’s the unix dictionary file). How would I unit test the calculations? Do I literally have to manually calculate everything and test that the result is right? I have a feeling that this defeats the whole purpose of unit testing. I’m not taking any input through stdin.
That’s not what unit-testing is about!
Unit-test means (not complete and not the by-the-book definition):
This guy (Gary Bernhardt) has some interesting practical examples of what testing and unit-testing means.
Update for some clarifications:
“1. Would I test that the file opened?”
Well you could do that, but what would be the “UNIT” for that? Keep in mind, that a test has just two solutions: pass and fail. If your test fails, it should (ideally must) have only one reason for that: Your unit(=function) sucks! But in this case your test can fail, because:
* the file doesn’t exist
* is locked
* is corrupted
* no file-handles left
* out of memeory (big file)
* moon- phase
and so on.
so what would a failing (or passing) “unit” test say about your unit? You don’t test your unit alone, but the whole surrounding enviroment with it. That’s more a system-test!
If you would like to test nontheless for successful file-opening you should at least mock a file.
“2 … How would I unit test the calculations? Do I literally have to manually calculate everything and test that the result is right?”
No. You would write test for the corner- and regular-cases and check the expected outcome against the processed one. The amount of tests needed depends on the complexity of your calculations and the exceptions to the rule.
e.g.:
I hope i made myself clearer!