Do you want to start writing unit tests and you don’t know how to start? Were you asked to write some unit tests on a past interview? Let’s see what is a unit test and how to write your first unit tests in C#.

What is a unit test?

The book The Art of Unit Testing defines a unit test as “an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work.”

From the previous definition, a unit of work is any logic exposed through public methods. Often, a unit of work returns a value, changes the internals of the system, or makes an external invocation.

If that definition answers how to test public methods, we might ask: ‘What about private methods?’ Short answer: we don’t test them. We test private methods when we call our code through its public methods.

In short, a unit test is code that invokes some code under test and verifies a given behavior of that code.

Why should we write unit tests?

Have you ever needed to change your code, but you were concerned about breaking something? I’ve been there too.

The main reason to write unit tests is to gain confidence. Unit tests allow us to make changes, with confidence that they will work. Unit tests allow change.

Unit tests work like a “safety net” to prevent us from breaking things when we add features or change our codebase.

In addition, unit tests work like a living documentation. The first end-user of our code is our unit tests. If we want to know what a library does, we should check its unit tests. Often, we will find not-documented features in the tests.

Your unit tests work like a safety net. Photo by Farzanah Rosli / Unsplash

What makes a good unit test?

Now, we know what is a unit test and why we should write them. The next question we need to answer is: ‘What makes a test a good unit test?’ Let’s see what all good unit tests have in common.

Our tests should run quickly. The longer our tests take to run, the less frequent we run them. And, if we don’t run our tests often, we have doors opened to bugs.

Our tests should run in any order. Tests shouldn’t depend on the output of previous tests to run. A test should create its own state and not rely upon the state of other tests.

Our tests should be deterministic. No matter how many times we run our tests, they should either fail or pass every time. We don’t want our test to use random input, for example.

Our tests should validate themselves. We shouldn’t debug our tests to make sure they passed or failed. Each test should determine the success or failure of the tested behavior. Imagine we have hundreds of tests and to make sure they pass, we have to debug every one of them. What’s the point, then?

#unit testing #c# #mstest

Unit Testing 101: Write your first unit test in C# with MSTest
1.20 GEEK