.NET Core Unit Testing - Mock IOptions

前端 未结 8 901
难免孤独
难免孤独 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 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 _options = Options.Create(new SampleOptions()
            {FirstSetting = "firstSetting"});
    
        public SampleRepoTests()
        {
            _mocker.Use(_options);
            _sampleRepo = _mocker.CreateInstance();
        }
    
        [Fact]
        public void Test_Options_Injected()
        {
            var firstSetting = _sampleRepo.GetFirstSetting();
            Assert.True(firstSetting == "firstSetting");
        }
    }
    
    public class SampleRepo : ISampleRepo
    {
        private SampleOptions _options;
    
        public SampleRepo(IOptions options)
        {
            _options = options.Value;
        }
    
        public string GetFirstSetting()
        {
            return _options.FirstSetting;
        }
    }
    
    public interface ISampleRepo
    {
        string GetFirstSetting();
    }
    
    public class SampleOptions
    {
        public string FirstSetting { get; set; }
    }
    

提交回复
热议问题