C# Unit Tests


Wikipedia says: “Unit tests are typically automated tests written and run by software developers to ensure that a section of an application (known as the “unit”) meets its design and behaves as intended.” A unit could be an entire module, but it is more commonly an individual function or procedure. We have code testing code. You need to write the code that tests your code. Suppose you have a simple function called DoubleIt(). It takes one parameter in and outputs twice the amount. You could create a unit test for that.

YouTube Video by Tim

YouTube has a few videos on unit testing with C#. One such video is called Intro to Unit Testing in C# using XUnit by IAmTimCorey. It’s very good for beginners. In the VS IDE, you can download xunit with the NuGet package manager. Tim has a very simple app that he wants to add unit testing to.

Tim’s using Visual Studio Community 2017 in the video, which is good for me because that’s what I’m using. He’s also using VS Community inside Azure. Tim Corey also gives us some perspective on the importance of doing unit tests. He says they are important, but recommends that we don’t go to the extreme where we insist that every piece of code should be written under TDD (test-driven development) where tests are written before code. We can write tests after the code is written. That would be much better than no tests at all. Also when starting to learn unit testing, start off simple and small (keep it simple). I like this video because Tim does start small and simple.

With simple functions to test, writing the code itself is fairly easy. In my opinion, the whole process of setting up and running the tests is more difficult. With complex functions or modules to be tested, writing the test will, of course, be more difficult.

YouTube by Mosh

Here is a YouTube video on unit testing called Unit Testing C# Code – Tutorial for Beginners by Mosh Hamedani. This video is 44 minutes long. It is part of Mosh’s Udemy course on unit testing. To write unit and integration tests you need a framework. Here are three examples: MSText, NUnit, and xUnit. Mosh writes the first unit test at time 16:15, but if you are new to this, don’t skip the previous parts. Mosh briefly discusses test-driven development (TDD) at time 38:25.

I created a TestNinja solution with the two projects and tried this one myself. I called the project TestNinja. It’s a console app.