.NET Core Unit Testing - Mock IOptions

前端 未结 8 849
难免孤独
难免孤独 2020-12-12 17:55

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

相关标签:
8条回答
  • 2020-12-12 18:32

    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.

    0 讨论(0)
  • 2020-12-12 18:32

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题