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 te
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.
You can always create your options via Options.Create() and than simply use AutoMocker.Use(options) before actually creating the mocked instance of the repository you're testing. Using AutoMocker.CreateInstance<>() makes it easier to create instances without manually passing parameters
I've changed you're SampleRepo a bit in order to be able to reproduce the behavior I think you want to achieve.
public class SampleRepoTests
{
private readonly AutoMocker _mocker = new AutoMocker();
private readonly ISampleRepo _sampleRepo;
private readonly IOptions<SampleOptions> _options = Options.Create(new SampleOptions()
{FirstSetting = "firstSetting"});
public SampleRepoTests()
{
_mocker.Use(_options);
_sampleRepo = _mocker.CreateInstance<SampleRepo>();
}
[Fact]
public void Test_Options_Injected()
{
var firstSetting = _sampleRepo.GetFirstSetting();
Assert.True(firstSetting == "firstSetting");
}
}
public class SampleRepo : ISampleRepo
{
private SampleOptions _options;
public SampleRepo(IOptions<SampleOptions> options)
{
_options = options.Value;
}
public string GetFirstSetting()
{
return _options.FirstSetting;
}
}
public interface ISampleRepo
{
string GetFirstSetting();
}
public class SampleOptions
{
public string FirstSetting { get; set; }
}