Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize IOption<AppSettings> for unit testing a .NET core MVC service?

I have a .NET core MVC rest service. I have a controller I wish to test. This controller has a constructor argument of IOptions where AppSettings is my class for config settings ( I store my database connection string in it). It gets injected from the setup in ConfigureServices in Startup.cs

The rest service works. My problem is I've set up a MSTest test project to test the service. I can't figure out how to initialize an instance of IOptions to satisfy the constructor of my controller.

like image 935
James Wierzba Avatar asked Dec 30 '16 16:12

James Wierzba


People also ask

What is the unit test in ASP NET Core using MSTest?

In this article, I will explain about the unit test in asp.net core using MSTest. There are three different test frameworks which are supported by the unit test with asp.net core: MSTest, xUnit, and NUnit, which allow us to test our code in a consistent way.

How do I use configuration values in my application settings?

An easy and typesafe way to use configuration values in your .NET core applications is through IOptions<T>. This allows you to create a settings section in your appsettings.json:

How do I run a unit test in Visual Studio 2019?

Type unit test in the search box, select C# as the language, and then select the C# Unit Test Project for .NET Core template, and then click Next. Starting in Visual Studio 2019 version 16.9, the MSTest project template name changed from MSTest Unit Test Project (.NET Core) to Unit Test Project.

Where does MSTest inject the rest service?

It gets injected from the setup in ConfigureServices in Startup.cs The rest service works. My problem is I've set up a MSTest test project to test the service.


1 Answers

I discovered the answer shortly after posting the question.

use Helper class Microsoft.Extensions.Options.Options

Creates a wrapper around an instance of TOptions to return itself as IOptions

AppSettings appSettings = new AppSettings() { ConnectionString = "..." }; IOptions<AppSettings> options = Options.Create(appSettings); MyController controller = new MyController(options); 
like image 138
James Wierzba Avatar answered Sep 17 '22 04:09

James Wierzba