Test doubles

Test doubles are functions and classes that aid in the testing process by allowing you to either verify functionality or bypass a dependency that would otherwise be difficult to test. Test doubles are used at all levels to isolate the code being tested. Many times, the need for a test double drives the architecture of the code.

The DateTime object in C# is an example of when this is the case. System.DateTime is part of the .NET Framework, and normally you wouldn’t think that you would abstract this in your code. The instinct of most developers is to simply reference it in a using statement and then access DateTime.Now directly within their code.

A test that can't be repeated is a bad test.

This is usually difficult to test. If we were to try to test a method using DateTime.Now, we would be unable to prevent DateTime.Now default functionality. DateTime.Now returns the current date and time stored in a DateTime object. Not having the ability to manipulate the return of this object causes our tests to be unpredictable and unrepeatable. A test that can't be repeated is a bad test.

Many developers already understand the need for predictability. You may have heard the phrase, If it can't be reproduced, it's not a bug or a similar sentiment. This is because, in order to verify that we have fixed a bug, we must be able to predictably repeat the error. This way, once the steps to reproduce it no longer produce the bug, we can confidently say that the bug is fixed. At least we can for that series of steps.

Testing is no different from bug fixing; it follows all the same steps. We just know exactly what caused the bug; the code hasn't been written yet, or the refactoring we just attempted failed.

Creating test doubles can get a little involved at times. For this reason, frameworks to support the creation of these test doubles have been created for nearly every language that has a testing framework. The frameworks are generally referred to as mocking frameworks or libraries. In C#, the predominant framework currently in use is Moq, pronounced mock. Similarly, in JavaScript, the most referenced mocking library seems to be Sinon, pronounced sign on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.70.88