Skip to main content

Deep dive in unit testing

These days each product reaching market is labelled as top quality - no matter if it`s a toy or a car or an application. Everyone talk about quality, quality is everywhere and at the same time quality by nature is a tricky thing to define and measure. To give you an example, imagine a two new brand cars from a two different car manufacturers like for example BMW and Fiat. Dealers of both brands will tell you that their cars are top quality and in fact that is true! The problem starts when you try to understand what top quality means for both car manufacturers - what are their standards of quality. What Fiat can consider as top quality might be completely not acceptable for BMW. From client perspective what really important is to understand how to measure quality in a standards driven way. As an example let's compare a European car safety performance assessment rating for both brands (NCAP is rated from 1 to 5 stars where 5 stars is given for most safety cars). In this rating cars manufactured by Fiat sometimes get 5 stars but usually it`s below 5. At the same time BMW gets must get 5 otherwise car won’t be released. Please remember that both car manufacturers claims their car to be top quality (!!) and without having a standard in place (like NCAP) from client perspective it`s difficult to understand quality standards baseline for each brand.
Having a common standards is also very important in the software development world as the same quality rules applies to all software products. All applications or systems might be considered as top quality as without common standards it`s just matter of defining what the quality means. For example having only one production outage per week might be considered as top quality by some teams when other teams do not tolerate any outage at all.
"A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behaviour of that unit of work" (Unit Testing Lessons in Ruby, Java and .NET - The Art Of Unit Testing - Definition of a Unit Test). Above definition describes unit test to be a piece of code calling other small (atomic) piece of product code under test. For people who are new in development process this might sound very bizarre as a benefit of having unit tests in a project is not clearly defined. However unit tests are one of the most useful and powerfully tool in the developer hands. The advantages of having unit tests implemented are:
  • Cut dependencies - the most powerful feature of unit tests is that a piece of code can be executed in isolation (without dependencies fully in place) by using mock(s). Mock objects are simulated objects that mimic the behaviour of real objects in controlled ways. Therefore a product code which for example makes call to external API or database can be easily tested by 'mocking dependencies' (without a need of having other components setup) in such case dependencies still exists but it replaced by mock object.
  • Execution time - unit tests are fast, really fast. Short time of a test execution is achieved by cutting dependencies and isolating code which allows to execute entire test in memory - without any network traffic.
  • Fail fast - by the nature of defects, it`s more expensive and time consuming to fix potential bug in Production or UAT rather than on local development environment. Unit tests help in detection of defects at very early stage of development process. As per fast execution time and mocks each developer can run unit tests on local environment. However this manual activity (it`s good habit) can be easily automated as all unit tests can be executed as a part of gated check-in build in TFS (code commit process). In such a scenario a code change will be accepted only if all unit tests will pass.
  • Continuous delivery - as unit test are self-contained and therefore don`t need any pre-existing data in order to execute. This feature allow to run it as a part of continuous delivery process straight after code merge between for example UAT and Production branches. Such an approach allows to ensure that code merge did not introduce any unexpected regression or defect.
  • Enforces good design - implementing unit tests it not that easy but it`s not hard as well. Certain product code architecture must be put in place prior to writing tests itself. Thankfully just by following SOLID principles code unit testability can be achieved pretty fast. Moreover what is important is that following SOLID principles makes code even more open for change (agile) as well as easier to maintenance.
  • Facilitates change - introducing any change is any piece of code always brings a risk. This risk can be easily mitigated when product has high unit test coverage. Running unit tests after completing development changes on a local development environment can help to identify potential regression in a code and fix it straightaway.
  • Allow to measure code coverage – running a unit tests against source code under test provides a useful matrix of a percentage of executed (tested) lines of code by subset of unit tests per project.


I already described what unit tests are and how can be used to improve a product quality. However at this stage there are three additional questions in regards to unit testing:
Q: Who should develop unit tests?
A: In Agile Scrum world there is no separation in a team for Developer and Tester roles – all members of a developments teams are consider to be developers. To answer this question I encourage you to think about unit testing as way for developers (all team members) to proof that code works as expected. This means that is up to each team member who introduced any change in the code to actually add/modify/deprecate relevant unit tests. Without following such an approach developer cannot proof that code he/she implemented is actually functional. The good practice here is to change a standard development process (implement code -> test code) and start using a TDD (Test Driven Development) approach. Additionally the TDD approach help to solve another common problem with testing which is about time allocation. Unfortunately it`s very common patter across agile development teams to actually deprioritize (drop) testing work at the end of sprit under pressure of deadlines. With TDD tests goes first (before actual product code change) so that time allocation is always there.
In summary unit tests verifies quality of both code changes and overall product. It should be up to entire development team to make sure that enough time is allocated for testing and tests are implemented on time for each change.
Q: How to encourage your team to implement unit tests?
A: A short answer is that you should not have to do that. All developers should understand how beneficial is to actually have unit tests in place. Unfortunately this is not always true and in some cases a mentoring effort is required in order to explain to your team the benefits of unit testing. Additionally other aspects of software development process like code reviews and measuring code coverage during build might be used.
Q: When to run unit tests?
A: The beauty of unit tests is that it’s very fast and easy to run. As unit tests use mock to cut dependencies each developer can run thousands of it from his/her local development environment in a few seconds. This is very powerful tool as by being able to run set of tests against a project with a high code coverage means that each developer can check impact of a code change on entire product. This gives all team members a great tool which helps to avoid regressions in product code so that they can save more time. Additionally unit tests can be executed automatically by CI as a part of change commit to code repository (code check-in) so that breaking code change has no chance to get into repository as it will be rejected in a case of unit test failure.
The last question remains. Is it worth to make investment in unit tests? Of course it is! It’s never too late to bring some improvements for both your product and your team. Time invested in unit tests implementation might initially significant but will reduce in time and investment will certainly pay off.

Popular posts from this blog

Full-Text Search with PDF in Microsoft SQL Server

Last week I get interesting task to develop. The task was to search input text in PDF file stored in database as FileStream. The task implementation took me some time so I decided to share it with other developers. Here we are going to use SQL Server 2008 R2 (x64 Developers Edition), external driver from Adobe, Full-Text Search technology and FileStream technology.Because this sems a little bit comlicated let`s make this topic clear and do it step by step. 1) Enable FileStream - this part is pretty easy, just check wheter You already have enabled filestream on Your SQL Server instance - if no simply enable it as in the picture below. Picture 1. Enable filestream in SQL Server instance. 2) Create SQL table to store files  - mainly ther will be PDF file stored but some others is also be allright. Out table DocumentFile will be created in dbo schema and contain one column primary key with default value as sequential GUID. Important this is out table contains FileStream

Playing with a .NET types definition

In the last few days I spent some time trying to unify structure of one of the project I`m currently working on. Most of the changes were about changing variable types because it`s were not used right way. That is why in this post I want to share my observations and practices with you. First of all we need to understand what ' variable definition ' is and how it`s different from ' variable initialization '. This part should be pretty straightforward:   variable definition  consist of data type and variable name only <data_type> <variable_name> ; for example int i ; . It`s important to understand how variable definition affects your code because it behaves differently depends weather you work with value or reference types. In the case of value types after defining variable it always has default value and it`s never null value. However after defined reference type variable without initializing it has null value by default. variable initialization  is

Persisting Enum in database with Entity Framework

Problem statement We all want to write clean code and follow best coding practices. This all engineers 'North Star' goal which in many cases can not be easily achievable because of many potential difficulties with converting our ideas/good practices into working solutions.  One of an example I recently came across was about using ASP.NET Core and Entity Framework 5 to store Enum values in a relational database (like Azure SQL). Why is this a problem you might ask... and my answer here is that you want to work with Enum types in your code but persist an integer in your databases. You can think about in that way. Why we use data types at all when everything could be just a string which is getting converted into a desirable type when needed. This 'all-string' approach is of course a huge anti-pattern and a bad practice for many reasons with few being: degraded performance, increased storage space, increased code duplication.  Pre-requirements 1. Status enum type definition