.NET Core Unit Testing - Mock IOptions

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

    You can avoid using MOQ at all. Use in your tests .json configuration file. One file for many test class files. It will be fine to use ConfigurationBuilder in this case.

    Example of appsetting.json

    {
        "someService" {
            "someProp": "someValue
        }
    }
    

    Example of settings mapping class:

    public class SomeServiceConfiguration
    {
         public string SomeProp { get; set; }
    }
    

    Example of service which is needed to test:

    public class SomeService
    {
        public SomeService(IOptions config)
        {
            _config = config ?? throw new ArgumentNullException(nameof(_config));
        }
    }
    

    NUnit test class:

    [TestFixture]
    public class SomeServiceTests
    {
    
        private IOptions _config;
        private SomeService _service;
    
        [OneTimeSetUp]
        public void GlobalPrepare()
        {
             var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", false)
                .Build();
    
            _config = Options.Create(configuration.GetSection("someService").Get());
        }
    
        [SetUp]
        public void PerTestPrepare()
        {
            _service = new SomeService(_config);
        }
    }
    

提交回复
热议问题