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.
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.
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:
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.
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 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With