Unit Testing

by Andy for Project
Unit Testing

A unit test is an automated test that makes calls to your code to check that they are returning output or working as expected. For example say I had written a calculator, inside this calculator there may be a method that adds two numbers together. It would take in to integers, and inside the method it would add them together and return you the result. Wouldn’t it be handy to know that this method is always working.

“But it’s a simple method and I would have to spend additional time writing tests, what’s the benefit I hear you ask” Okay so this is a simple example, but when you move onto more complex pieces of code it would be much more efficient in the long run to be able to say that all the code is working as expected. Granted it would take longer at the start to write these additional tests but for example let’s say you didn’t have them and someone pesky monkey went in and modified your calculator code to turn the add function into a minus. With a properly written unit testing you’ll be able to see this straight away, without it you’ll be spending your time scouring through code to see what is going wrong.

So how do we begin? Here is the calculator add method we spoke about earlier.


To test this you could write a test in your current to code to check that the method returns 20 when 15 and 5 are entered as x and y respectively. If it doesn’t throw some kind of exception to the system. Or you could write a unit test to automatically run that calculation.

To begin you’ll need to add a testing project to your current solution:

To test the method you’ll need to write a new test class, as we are using .net core in this example, we use the [Fact] attribute above a method as opposed to [TestMethod] as seen elsewhere.

This test will check the result and compare it to the expected value. The expected value is always put first in the assert test. The important part of this test is the Assert section, there are many different types of assert to test results against for a full list see here.

To run the tests in visual studio go to the menu at the top, click tests > run > and then all tests.

This will open a window that’ll show the status of the Test results.

Overall although this additional testing takes time the benefits in the long run you can see the benefits from the start, and it will hopefully allow you to find bugs in your code a lot quicker.


jQuery for the script guy
Prev post JWT - If your name's not on the list...

I love a good metaphor when learning a new topic. I recently started using JSON…

jQuery for the script guy
Next post jQuery for the script guy

jQuery is the most used Javascript library in the world. It’s also one of the…