DEV Community


Posted on

glazed-donut: Unit Testing

Unit Testing

To write unit tests for the glazed-donut repo, I decided to choose xUnit as my unit testing framework, because this is something I have used before. Also, after going through other unit testing frameworks available for C#, such as NUnit and MSTest, I just liked xUnit's syntax the most, it seemed more consistent and straightforward to me.

xUnit is an open source testing framework for C#, F#, and Visual Basic. It allows you to write unit tests.

How to set up xUnit in your project?

To set up xUnit in your project, you just have to follow these simple steps (in Visual Studio):

  1. Right click on your solution and select "Add New Project".

  2. Choose "xUnit Test Project":

Image description3. Include a reference to your project solution (Right click on your unit test solution --> Add --> Project Reference --> Check on the solution you want to reference --> click Ok)

One thing I learned about Unit Testing this time:

I learned that test shouldn't test how my code works, they should test how my code is supposed to work. During the process, I was trying to test what my code was doing and make a unit test based on that. The reason why we don't want to test how our code works is because the code may have bugs or some unexpected behavior that we may not find out about, if we try to mimic the functionality of methods into our unit tests.

For example, let's say you have a method that accepts a string and only covers a scenario when that string is valid. When writing a unit test to cover a negative scenario, you noticed that if someone passed a null value, your code wouldn't know how to deal with that since it doesn't cover that case. Instead of just not knowing what to return for that case in your unit test or skipping writing a negative unit test, it would be better to fix your code to actually cover that scenario and then see if your method would pass that unit test.

Would I recommend writing unit tests?

- YES!

From my experiences with unit tests, I would say that I would do testing in the projects I will be working on, even through it can be annoying, because unit testing tells us the following:

  • it documents my program - if someone would have changed something in your function by accident, you would now that because a unit test for that function would fail.

  • it tells us that all the functions work as intended - because when we write unit tests, we think through positive and negative scenarios, and we are sure that our code covers everything.

  • it reduces amount of potential/existing bugs in your code

In conclusion, I think that Unit Tests would be a great addition to anyone's code. It definitely takes a lot of practice to master writing them, but it is going to worthwhile in the long run.

Discussion (0)