Is it possible to unit-test a class whose main task is to interact with the file system? Well, for example, I need to test a class that provides the ability to write / read bits from a file. How can I do this? You can, of course, write a file with some test data, and in the test itself check that it is the data that is being read. It seems to me like a crutch. Is this true and what are some other ways to test the work of this class?
1 answer
Let's try to go through the problem in the style of TDD:
- What public methods should this class have? Let it be read only
Read(path, offset, count)andWrite(name, offset, count). Until we write their code, while we need to figure out how we could test them? Let's write a few tests (which, by the way, will help us more accurately describe the behavior and interface of the class):
- Read something from the file and check that what you read is read.
- What should happen if a command is given to read 100 bytes from a 50 byte file? Return 50 bytes, return an error / exception, or return 100 bytes of which the last 50 are empty? Choose an option and write a test on it.
- What should happen if the file does not exist or is inaccessible? Again, choose the "right" behavior and write a test on it.
- Do we allow the transfer of a negative
offsetvalue, and what it will mean (for example, reading from the end, not from the beginning). We write the test. - Will we support reading / writing on the local network? Long file names (260+)? Record in system folders (with the requirement of the admin rights)?
- What else should work and what can go wrong .. think over the desired behavior and write tests on it.
Repeat the same for the write method to the file. Do not strive immediately to provide EVERYTHING. Consider only what you need in the foreseeable future (according to your TK).
Now you can pause, and summarize all those moments and subtleties that surfaced in the design of tests. Take another look at them, estimate which situations require private methods and functions that are common to read and write (for example, checking the existence of a file, or size).
But only now you can start writing the code of the class itself read / write to the file!
We met some other condition, or a boundary case in the development process - great, write a test on it, and then a code.
During the operation of the class, a bug emerged - also excellent, write a test to it, and only then correct the bug (and test it to verify that it is fixed, and that nothing has broken in the process of fixing).