Last updated on 2022-06-03
What is a unit test?
A unit test is a small function that calls a function from our “real” program and verifies the results from the function are the expected results.
For example, if we have a function that calculates the sum of two integers, and we pass it a 2 and a 4, we’d expect to get a 6 back from it.
Our unit test function would call the “add two numbers” function, passing in a 2 and a 4, and confirm the function returns a 6.
Why do I need unit tests?
This is a small, simple function. It really doesn’t need a unit test. But, as functions get larger and more complex, unit tests let us know all the paths through the functions work correctly.
They also let us know if a future change broke some existing logic. After each change to the code, we can re-run the unit tests and see if they all work. That way, we can feel safe our change didn’t break something else in the program.
How to add unit tests
- Add a unit test project to your solution
- It must be the same type of .NET as the class library you’ll test with it
- It can be MSTest, xUnit, or nUnit. They all work about the same with, with a few syntax differences.
- Add a project reference in your Test project to the Class Library project(s) you’ll be testing in the unit tests
- Create a class in the Test project for your unit tests
- Add “using” directives to the namespaces needed for the classes you’ll be testing
- Create “public void” functions for your unit tests
- Give them descriptive names, to make it more obvious what the problem is if the test fails
- Add the correct attribute to the function, so your unit test runner recognizes the function as a unit test function.
- Test that your Asserts succeed and fail (if you put in a bad assertion)
- It’s possible to have bad logic in the unit test code, which may give a false positive for the Assert
Functions that use external resources
In this video, the function being tested did not use any external resources, like a database, web service, or the file system.
If you want a unit test for a function that uses an external resource, you’ll probably want to “mock” the external resource. This way, if there’s a problem with the database/web service/file system, the test can still pass. Remember, the unit test is to test the calculations of the function – not that the database is running and has the expected values in it.
I’ll show how to write unit tests for external resources in another video.