How to write tests where conditions like the following arise:
- Test user Input.
- Test input read from a file.
- Test input read from an environment variable.
It’d be great if someone could show me how to approach the above mentioned scenarios; it’d still be awesome if you could point me to a few docs/articles/blog posts which I could
read.
All three situations you’ve described are where you need to specifically go out of your way to ensure you are using loose coupling in your design.
Do you really need to unit test Python’s
raw_inputmethod? Theopenmethod?os.environ.get? No.You need to set up your design so that you can substitute other ways of retrieving that input. Then, during your unit tests, you’ll throw in a stub of some sort that doesn’t actually call
raw_inputoropen.For instance, your normal code might be something like:
The session looks like:
Then your test will be like:
Keep in mind that you should not have to test a language’s IO facilities (unless you’re the one designing the language, which is a different situation entirely).