Dependency Injection (DI) in .NET Core and .NET 5 (C#) Unit Tests
Introduction
Now that you have written your initial code and logic, you are ready to start writing some unit tests. Wouldn’t it be nice if you could just copy and paste your Startup.cs
Dependency Injection (DI) setup and use it in your tests project? This post will help you get there.
Assumptions
- You already have a high level understanding of what Dependency Injection (DI) is and how .NET uses it. If not, there are a lot of greats posts here on Medium or you can read about it through Microsoft docs.
Startup.cs
Let’s start by looking at a snippet of Dependency Injection (DI) code in a Startup.cs
file.
For this post we’ll be looking at a sample Authentication API that I have developed myself. It uses .NET 5, C#, JWT (JSON Web Tokens) and Repository Pattern. Yours will usually look very similarly, with differences in what classes are Dependency Injected (DI).
Unit Tests project
Now, let’s see what this looks like in a Unit Tests project. In this example, I use a public static class Helper
to assist in the setup of all Dependency Injection (DI).
Once you have the Provider()
method, you can make it generic so you can get any Dependency Injected (DI) service by putting it in a wrapper method.
Afterwards, you can use it anywhere in your Unit Tests project. Below is an example of using it in a UserRepositoryTests.cs
file.
That’s it! Now you can use the Helper.GetRequiredService<T>
in any .cs
file of your Unit Tests project!
Conclusion
Dependency Injection (DI) is awesome and helpful in setting up your projects. It’s even more awesome when you can simply port it to your Unit Tests project.
Full details
Frameworks
- .NET 5 and .NET Core 3.x
Authentication service source code — fully functioning service that implements this approach
Authentication service source code jump to