55

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.

James Wierzba
  • 16,176
  • 14
  • 79
  • 120
  • You might want to look into a mocking framework like NSubstitute or Moq. This will let you create a mock IOptions object that you can pass into the instance of your controller in the unit tests. – Matt Dalzell Dec 30 '16 at 16:40
  • @IsThatQueeblo I figured out a simple way to initialize an instance of `IOption` (i posted an answer) however I also need to mock some headers in the Http request. I imagine those mocking frameworks will provide that as well? – James Wierzba Dec 30 '16 at 16:44
  • 1
    Possible duplicate of [.Net Core Unit Testing - Mock IOptions](http://stackoverflow.com/questions/40876507/net-core-unit-testing-mock-ioptionst) – Nkosi Dec 30 '16 at 16:54

1 Answers1

101

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);
James Wierzba
  • 16,176
  • 14
  • 79
  • 120