.Net Core Unit Testing - Mock IOptions

Jak
Jak
908 Points
132 Posts

I have a .NET core rest api service and controller. I'm using xUnitTest to test the controller and service.
Service has a constructor argument of IOptions where AppSettings is my class for config settings.

In my unit test project to test the service/controller. I'm not able to mock/initialize an instance of IOptions to satisfy the constructor of my controller:

public class SampleRepoTests
{
    private IOptions<SampleOptions> _options;
    private SampleRepo _sampleRepo;


    public SampleRepoTests()
    {
        //Not sure how to populate IOptions<SampleOptions> here
        _options = options;

        _sampleRepo = new SampleRepo(_options);
    }
}
Views: 13473
Total Answered: 2
Total Marked As Answer: 1
Posted On: 24-Apr-2020 04:55

Share:   fb twitter linkedin
Use Microsoft.Extensions.Options.Options
 - beginer  25-Apr-2020 01:59
Answers
Alice
Alice
32 Points
1 Posts
         

Use Helper class Microsoft.Extensions.Options.Options

Options.Create() a wrapper around an instance of TOptions to return itself as IOptions

SampleOptions sampleOptions = new SampleOptions() { ConnectionString = "..." };
IOptions<SampleOptions> options = Options.Create(sampleOptions);
Posted On: 25-Apr-2020 02:03
Smith
Smith
2890 Points
78 Posts
         

Check following code:

public class SampleRepoTests
{
    private IOptions<SampleOptions> _options;
    private SampleRepo _sampleRepo;


    public SampleRepoTests()
    {
        // mock the settings here
        var sampleOptions = new SampleOptions(){ /* here, assign value to the properties*/ };
        
        _options = Options.Create(sampleOptions);

        _sampleRepo = new SampleRepo(_options);
    }
}

For this following package to be installed

Microsoft.Extensions.Options

And import package as:

Using Microsoft.Extensions.Options;
Posted On: 30-Apr-2020 05:31
Thanks
 - Jak  01-May-2020 21:12
 Log In to Chat