C# – How to unit test code that reads and writes to the console

When you’re unit testing code that uses the console IO methods, you’ll need a way to automate the input and a way to capture the output. There are two ways to do this: Redirect the console IO. Wrap the console IO method calls and mock out the wrapper. In this article, I’ll show how to … Read more

How to use NLog in ASP.NET

When you want to use NLog in ASP.NET, the first step is to install and configure NLog. Then you can either use NLog directly or fully integrate NLog and ASP.NET. Use NLog directly if you prefer to have static ILogger properties, instead of using dependency injection. The downside of this approach is that you’ll have … Read more

C# – How to unit test code that uses Dapper

Dapper makes your code difficult to unit test. The problem is that Dapper uses static extension methods, and static methods are difficult to mock out. One approach is to wrap the Dapper static methods in a class, extract out an interface for that wrapper class, and then dependency inject the wrapper interface. In the unit … Read more

C# – Default method implementations and constants in interfaces

Starting in C# 7, you can add default method implementations (and constants) to interfaces, like this: This outputs the following: Microsoft’s stated purpose for this feature is that it allows you add methods to an interface without breaking existing implementing classes. That’s nice, but it weakens the concept of interfaces (forcing implementers to adhere to … Read more

How to mock static methods

The need to mock static methods in order to add a unit test is a very common problem. It’s often the case that these static methods are in third-party libraries. There are many utility libraries that are completely made up of static methods. While this makes them very easy to use, it makes them really … Read more