.NET Core Unit Testing - Mock IOptions<T>

Matt picture Matt · Nov 29, 2016 · Viewed 64.1k times · Source

I feel like I'm missing something really obvious here. I have classes that require injecting of options using the .NET Core IOptions pattern(?). When I unit test that class, I want to mock various versions of the options to validate the functionality of the class. Does anyone know how to correctly mock/instantiate/populate IOptions<T> outside of the Startup class?

Here are some samples of the classes I'm working with:

Settings/Options Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace OptionsSample.Models
{
    public class SampleOptions
    {
        public string FirstSetting { get; set; }
        public int SecondSetting { get; set; }
    }
}

Class to be tested which uses the Settings:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OptionsSample.Models
using System.Net.Http;
using Microsoft.Extensions.Options;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Dynamic;
using Microsoft.Extensions.Logging;

namespace OptionsSample.Repositories
{
    public class SampleRepo : ISampleRepo
    {
        private SampleOptions _options;
        private ILogger<AzureStorageQueuePassthru> _logger;

        public SampleRepo(IOptions<SampleOptions> options)
        {
            _options = options.Value;
        }

        public async Task Get()
        {
        }
    }
}

Unit test in a different assembly from the other classes:

using OptionsSample.Repositories;
using OptionsSample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;

namespace OptionsSample.Repositories.Tests
{
    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);
        }
    }
}

Answer

Necoras picture Necoras · Nov 30, 2016

You need to manually create and populate an IOptions<SampleOptions> object. You can do so via the Microsoft.Extensions.Options.Options helper class. For example:

IOptions<SampleOptions> someOptions = Options.Create<SampleOptions>(new SampleOptions());

You can simplify that a bit to:

var someOptions = Options.Create(new SampleOptions());

Obviously this isn't very useful as is. You'll need to actually create and populate a SampleOptions object and pass that into the Create method.