Unit test, making better designs

What I’m presenting here is an example for Unit tests making us change the design to make a better design for our application.
We see our example, in Figure1, what we have is a sample library for handling IMAP connections, that uses a wrapper over sockets, using Net_Socket (one of the software design practices, is not to depend on system calls, but wrap them up, so your application wouldn’t be dependent on the system calls limitation).

Figure1
Figure1

If we wanted to test the Mail_IMAP class, we see that there is a dependency on the Net_Socket, and we only want to test Mail_IMAP, not the integration with Net_Socket, also Net_Socket is kind of an expensive call. Which will lead us to the need to make our application with less dependencies, which is a good thing to do, making our applications more orthogonal.
So we do a good software design thing, and change the code so that we pass the Net_Socket connection through the constructor of the class, instead of calling it from inside, so we can replace the Net_Socket object with another one, when we need to do the test.

Figure 2
Figure 2

Now, when we write the stub for Net_Socket, we realize that we are replacing every function the application provides, not benefiting from anything the class already provides, also, as we need to use the same name, we need to make sure that the same name is not provided in the environment of the tests, …. more and more constraints.
So, in order for us to solve this issue, we introduce an interface, that Net_Socket provides (INet_Socket), and make the Mail_IMAP, use it, not the actual object.

Figure 3
Figure 3

What we do now, is make our stub object implements the interface needed, and then pass it to the Mail_IMAP constructor.

Hope this was useful, if you have any question, don’t hesitate to comment on this post 🙂

Happy coding,