What is Unit Testing and Why You Need to Learn It
In this post, I’m going to give you a brief introduction to unit testing and its benefits. So, let’s get started!
What is unit testing?
Unit testing is the practice of writing code to test your code and then run those tests in an automated fashion.
Here is an example. Imagine you have this function somewhere in your code. It’s a basic calculate function that takes an input and depending on some conditions, it returns different values.
public float CalculateTax(int input)
{
if (x) return ...;
if (y) return ...;
return ...;
}
If you want to test this function manually, you have to run your application, perhaps you have to login, or maybe do a few clicks here and there to get to a page where this function is used. Then, you have to fill out a form, submit it and verify if this function returned the right result. And then you have to repeat all these steps, each time using different values in your form.
Manual testing is expensive!
As you can see, this is very time-consuming. This workflow to test this function may take several minutes every time! Now to make matters worse, this is not the only function in your application. In a real application, you have tens or hundreds of functions like this! As your application grows in size and complexity, the time required to manually test all the different bits and pieces increases exponentially. So, that’s why we use automated testing.
With automated testing, you create a separate project for writing tests. In that project you’ll write code and directly call this function with different inputs and verify that this function returns the right output.
var result = CalculateTax(1);
Verify(result == 1.5f);
We refer to these types of tests as unit tests. With unit tests, we test a unit of the application in isolation without its external dependencies such as files, databases, web services, etc. Tests that include these external dependencies are called integration tests, and that’s the topic for another post.
Unit tests are repeatable!
The good thing about unit tests is that they are repeatable. You write them once and run them a million times! So, every time you change your code, every time you commit your code to a repository, and before deploying your application. With this approach, you can test all the execution paths in this function in a fraction of a second! You can write several hundreds or thousands of unit tests for various parts of your application, and run them all in just a few seconds.
Unit tests help you deploy with confidence!
If you properly cover your code with a comprehensive suite of tests, you can run these tests before deploying your application to the production. If you’ve broken something that used to previously work, you’ll know straight away. With unit tests you can catch more bugs before deploying our application and this means you can deploy with confidence.
Have you ever been in a situation where you deployed your application, left the office thinking everything is working, and then got a call from your boss or an end-user, telling you that one of the major functions of the application is not working? Then you had to go back to the office and you thought that was a quick fix, but you ended up staying there till midnight!
That’s why you should write tests: to reduce the number of defects or bugs that will go in the production. Note that I’m not saying that with unit tests you’re gonna release bug free software. That’s not true! But you can certainly reduce the number of bugs and improve the quality of your software.
Unit tests help you refactor with confidence!
Refactoring means changing the structure of your code without changing its behaviour. If you extract a few lines of a method into a separate private method, that’s refactoring. If you rename a method, that’s refactoring too. You’re changing the structure of your code to make it cleaner and more maintainable, but you’re not changing the functionality.
When you don’t have unit tests, every time you refactor your code, you have to manually test every part of the application that could be affected by your refactoring. And this is very painful because first of all, it’s time consuming, and second, as your application grows, you may forget about the parts that need to be tested! With unit tests, every time you refactor your code, you run your tests and make sure you didn’t accidentally break anything that used to previously work.
Unit tests help you write better code!
When writing tests, you’re forced to think about the edge cases of every function in your application. You write tests for these functions, giving them various inputs and make sure they behave as you expect. This will help you produce better quality software with less defects. A lot of bugs in our applications are the result of unforeseen edge cases. One of your functions receives an input that you forgot to predict and boom! It blows up! With unit tests, you make sure that every function works with different inputs under varying circumstances.
Also, applications written with unit testing in mind often have cleaner and more maintainable source code. That means smaller functions with a clear responsibility and few parameters.
Benefits of unit testing
So, to recap, unit tests help you:
- Test your code frequently and in less time
- Catch more bugs before deploying
- Deploy your application with confidence
- Refactor your code with confidence
- Write cleaner and maintainable code
You need to have unit testing on your resume!
If you’re a senior developer, you must know how to write unit tests! If you don’t know, you’re probably more of an intermediate-level developer even if you have a senior position at your company.
If you’re a junior/intermediate-level developer and want to become a senior developer, you must have unit testing on your resume to get a better job. Most good companies with good programmers practice unit testing these days.
Unit testing C# code
I’m currently working on a comprehensive course on unit testing for C# developers. In this course, I’ll take you from the ground and teach you how to write unit tests for your C# code. I’m planning to release this course by the end of October. If you’re interested to get this course with an early-bird discount, drop your email and join my mailing list. I won’t spam you, and you can unsubscribe at anytime.
What is your story with unit testing? Drop in the comments below and let us know!
If you enjoyed this post, please share it with others!
Hi Mosh, Any unit testing course for JS?
Not at the moment!
Plans for unit testing for JS?
what i hope you cover is how to unit test controllers in an mvc application using a mocking framework like moq. specifically using DI framework in new .net core.
I agree!
That would be great! I’ve always wondered how to test the repository pattern effectively, and web api, although I’ve taken a look at NancyFX which seems to have great unit testing modules.
I agree with that
Mosh, please include TDD. As much as ppl argue about this it’s in my view the single most powerful approach to developing robust software. Once the habit is established it’s a breeze and writing tests after the fact really isn’t ideal because it leaves gaps and doesn’t promote decoupled single responsibility classes/functions. Great work on ur other courses!
I am so impatient by this future course
I’m looking forward to this one!
Do you cover unit testing Web APIs?
Are you releasing a course on udemy any time soon regarding unit testing with c#?
I would like to see a course on unit testing MVC. The how is not too hard but I struggle with understanding why it’s important. I have seen breakage caused by partner URLs changing, or database values changing. It’s hard to imagine refactoring a controller and having it not return a view and no one noticing during normal development.
I will be looking for your unit testing course. I am looking for a way to unit test Entity Framework 6 using FakeItEasy or Moq and will probably be looking for the same with EF Core 2.0+ when I get around to using that with a new project. Thanks for the post and the courses you have been producing.
Just one point: You keep repeating that “unit test your function”. You should *never* *EVER* test a function. You can test your system behavior and that’s it.
If you read Kent Beck’s “Test Driven Development”, you’ll notice that he says that you should test *behaviour* and not *implementation*. When you test a function, you’re testing implementation — and there is a long discussion you can have that if you change your requirements in a way that won’t need a function anymore, your test will keep the function alive and prevent the compiler to mark it as dead code.
So, not: Do *not* test functions/classes/modules. Test your application behaviour.
PS: “unit testing” means that the test is a unit and depends only on itself. Nothing more, nothing less.
Unit testing the “public” method is testing the external behaviour and not the implementation.
Hi Mosh, with unit test you can test your code, but some times you have to test your code including the UI. How you can do this as automatic as possible?
Another thing that would be nice is how to add unit testing to an existing MVC 5 project. I look forward to your course because unit testing is something I definitely need to add to my skill set.
sounds good.
Hi Mosh, I thoroughly enjoy your vids on udemy along with my readings. Anyway, my universe is telling me I better be good at TDD as I was just passed over in a recent interview as they were big in TDD and I was not. So your post comes into my view then I find uncle bob’s article as well http://blog.cleancoder.com/uncle-bob/2017/10/04/CodeIsNotTheAnswer.html So I better get with the program. Thanks again
Thanks a lot Mosh for your great tutorials. I would like that you show in this course how to do unit testing using VSCode
Looking forward to your new course on C# Unit Testing! Thank you so much for all your work and passion!
Looking forward to enroll in this great course! How about a course for MVC + React?
So basically the Idea is “your code is broken, you just don’t know it yet.”!! but, with Unit Testing you know it before going into production!
Awesome article!
Thanks Mosh!
Hi Mosh. I hope you will also cover NUnit and XUnit. Thank you
Hey Mosh,
Any plans on unit testing C# and Angular?
Mosh nice job is a great article ! I was discouraged to learn unity testing but after read this article my mind change
Nice Article Mosh. Thanks
I have learnt a lot from your C# unit testing course, in Udemy.
I have found bugs through my code and understood dependency Injection in the best way.
Thanks!
Hi Mosh , was great as usual, could you please create React hook unit test course ,I have googled a lot ,I have not found e sy to understand ,I have got 3 course of unit test still is not obviously way for me to test my component
It looks like the attached source code doesn’t exist any more and cannot be downloaded?