The benefits of using unit tests in your code cannot be overstated. Not only do they serve as a powerful refactoring tool, but they also act as a design tool to improve the quality of your code. If your application currently lacks unit tests, now is the time to start the journey toward 100% unit test coverage.
Unit tests as a refactoring tool
Without unit tests, refactoring can be a tedious process. It typically involves attempting to run or compile your code, reading a single stack trace, and fixing a single bug. With unit tests, however, this process becomes much more efficient. When multiple unit tests fail, you can fix multiple bugs simultaneously, saving you significant time.
Unit tests as a design tool
To convince you further,learn about why integration tests are a scam and why you should write unit tests instead. Another favorite reason I love unit tests is that they are a fabulous design tool.
It's difficult to write simple tests for complicated code.
- John Solly
In addition to their usefulness as a refactoring tool, unit tests also serve as an excellent design tool. Writing simple tests for complicated code can be difficult, so the implementation probably has room for improvement. I followed the TDD approach for my blog "blogthedata.com" and found missing coverage across several files.
Name Stmts Miss Cover Missing
---------------------------------------------------------------------
blog/templates/blog/categories.html 42 2 95% 35-36
blog/templates/blog/home.html 47 19 60% 33-52
blog/templates/blog/search_posts.html 50 19 62% 36-55
blog/templates/blog/user_posts.html 37 19 49% 20-39
---------------------------------------------------------------------
TOTAL 1164 59 95%
I discovered that I had duplicated the same pagination code across multiple files in my application. Rather than writing separate tests for the same logic in various locations, I chose to refactor the code by moving it into a separate file and utilizing Django's {% include %} tag to inherit it into the four templates.
By taking this approach, I achieved 100% code coverage after re-running my tests, without having to write a single additional test. This is a great example of how unit tests can be used as a design tool to improve the quality of your code and make it more maintainable.
Comments
- No comments yet.
John Solly
Hi, I'm John, a Software Engineer with a decade of experience building, deploying, and maintaining cloud-native geospatial solutions. I currently serve as a senior software engineer at HazardHub (A Guidewire Offering), where I work on a variety of infrastructure and application development projects.
Throughout my career, I've built applications on platforms like Esri and Mapbox while also leveraging open-source GIS technologies such as OpenLayers, GeoServer, and GDAL. This blog is where I share useful articles with the GeoDev community. Check out my portfolio to see my latest work!
0