C# – How to unit test console output

There’s two ways to unit test code that writes to the console (Console.WriteLine() / Console.Write()): In this article, I’ll show how to do both options. Option 1 – Capture the output with Console.SetOut() Let’s say you want to unit test the following code that outputs to the console with Console.WriteLine(): You can unit test this … Read more

C# – Join strings with a separator, ignoring nulls and empty strings

Normally when you want to join strings using a separator, you’d use string.Join(). However, the problem with string.Join() is it doesn’t ignore nulls or empty strings. Take a look at the following examples: If you want to filter out nulls and empty strings, you can filter the list of strings yourself and pass it into … Read more

C# – Using the DynamicData attribute in unit tests

The purpose of parameterized tests is to eliminate duplicated tests. There are two ways to pass parameters into a parameterized test: the DataRow attribute and the DynamicData attribute. With DataRow, the problem is you can only pass in constants and arrays. You can’t pass in reference types. When you try to pass in reference types, … Read more

C# – Parameterized tests with MSTest v2

There are two steps for parameterizing a unit test when using the MSTest v2 framework (built-in default): Here’s an example: Parameterized unit tests are useful because you only need one test method for multiple test cases instead of one test method per test case. It’s a simple way to declutter your unit tests and make … Read more