66

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.

3
  • 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. Commented Dec 30, 2016 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? Commented Dec 30, 2016 at 16:44
  • 1
    Possible duplicate of .Net Core Unit Testing - Mock IOptions<T> Commented Dec 30, 2016 at 16:54

1 Answer 1

125

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.