Assuming an email implementation as simple as the accepted answer on this post, what can be the best way to write a unit test for the implementation? (I do not want to shoot emails to a valid recipient as part of testing the implementation)
Share
First, make the part responsible for sending / receiving pluggable. Just make sure you can switch the class / function / object responsible for connecting / sending / receiving messages to / from the server.
Second, make this part act as real thing. Make sure this class / function / object will fake original class’s / function’s / object’s behaviour as close as possible (take the same parameters, throw the same errors).
Third, fake different behaviours of this part during tests. Different behaviours of this class in different tests may include:
and, depending on what your module really does (and how flexible it is, eg. if it can be used by someone else for coding), you can also include these behaviours:
It really largely depends on what your module does. You need to test, if it does these things properly. Do not test
smtplibmodule, as it is already covered with tests. Do not test things irrelevant to your module – just things it does. It is possible, that some parts of your modules are untestable – in that case you have two options: change them to be testable, or leave them as they are (it is sometimes the most reasonable option for various reasons).