.NET Core Unit Testing - Mock IOptions

前端 未结 8 911
难免孤独
难免孤独 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:07

    Given class Person that depends on PersonSettings as follows:

    public class PersonSettings
    {
        public string Name;
    }
    
    public class Person
    {
        PersonSettings _settings;
    
        public Person(IOptions settings)
        {
            _settings = settings.Value;
        }
    
        public string Name => _settings.Name;
    }
    

    IOptions can be mocked and Person can be tested as follows:

    [TestFixture]
    public class Test
    {
        ServiceProvider _provider;
    
        [OneTimeSetUp]
        public void Setup()
        {
            var services = new ServiceCollection();
            // mock PersonSettings
            services.AddTransient>(
                provider => Options.Create(new PersonSettings
                {
                    Name = "Matt"
                }));
            _provider = services.BuildServiceProvider();
        }
    
        [Test]
        public void TestName()
        {
            IOptions options = _provider.GetService>();
            Assert.IsNotNull(options, "options could not be created");
    
            Person person = new Person(options);
            Assert.IsTrue(person.Name == "Matt", "person is not Matt");    
        }
    }
    

    To inject IOptions into Person instead of passing it explicitly to the ctor, use this code:

    [TestFixture]
    public class Test
    {
        ServiceProvider _provider;
    
        [OneTimeSetUp]
        public void Setup()
        {
            var services = new ServiceCollection();
            services.AddTransient>(
                provider => Options.Create(new PersonSettings
                {
                    Name = "Matt"
                }));
            services.AddTransient();
            _provider = services.BuildServiceProvider();
        }
    
        [Test]
        public void TestName()
        {
            Person person = _provider.GetService();
            Assert.IsNotNull(person, "person could not be created");
    
            Assert.IsTrue(person.Name == "Matt", "person is not Matt");
        }
    }
    

提交回复
热议问题