We may often come across a piece of code that was written without Unit Tests at all. In addition, the piece of code may be dealing with IO like file writing and reading, which makes it more difficult to Unit Test it when we are trying to refactor and modify. Let's suppose the code in question looks like this:
def writeInitialsToFile(filename, name, surname): initials = name + '.' + surname + '.' with open(filename, 'w') as file: file.write(initials)
def readInitials(filename): initials = None with open(filename, 'r') as file: initials = file.readline() return initials
A straightforward and bad idea would be to write a couple of Unit Tests that make use of a real file and simply test the reading and writing. Is therea a better way to test this code?
First of all, we need a way to replace the real file with something else. For both reading and writing we will now have a couple of functions, one that expects a stream fo…