Press "Enter" to skip to content

How to create basic unit tests for C# programs

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

  1. Add a unit test project to your solution
    1. It must be the same type of .NET as the class library you’ll test with it
    1. It can be MSTest, xUnit, or nUnit. They all work about the same with, with a few syntax differences.
  2. Add a project reference in your Test project to the Class Library project(s) you’ll be testing in the unit tests
  3. Create a class in the Test project for your unit tests
    1. Add “using” directives to the namespaces needed for the classes you’ll be testing
  4. Create “public void” functions for your unit tests
    1. Give them descriptive names, to make it more obvious what the problem is if the test fails
    1. Add the correct attribute to the function, so your unit test runner recognizes the function as a unit test function.
  5. Test that your Asserts succeed and fail (if you put in a bad assertion)
    1. 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.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.