我觉得我错过了一些非常明显的东西。我有类需要使用.Net Core IOptions模式注入选项(?)。当我去单元测试那个类时,我想模拟各种版本的选项来验证类的功能。有谁知道如何正确模拟/实例化/填充Startup类之外的IOptions?
以下是我正在使用的课程的一些示例:
设置/选项模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OptionsSample.Models
{
public class SampleOptions
{
public string FirstSetting { get; set; }
public int SecondSetting { get; set; }
}
}
要使用设置的测试类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OptionsSample.Models
using System.Net.Http;
using Microsoft.Extensions.Options;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Dynamic;
using Microsoft.Extensions.Logging;
namespace OptionsSample.Repositories
{
public class SampleRepo : ISampleRepo
{
private SampleOptions _options;
private ILogger<AzureStorageQueuePassthru> _logger;
public SampleRepo(IOptions<SampleOptions> options)
{
_options = options.Value;
}
public async Task Get()
{
}
}
}
与其他类不同的程序集中的单元测试:
using OptionsSample.Repositories;
using OptionsSample.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
namespace OptionsSample.Repositories.Tests
{
public class SampleRepoTests
{
private IOptions<SampleOptions> _options;
private SampleRepo _sampleRepo;
public SampleRepoTests()
{
//Not sure how to populate IOptions<SampleOptions> here
_options = options;
_sampleRepo = new SampleRepo(_options);
}
}
}
答案 0 :(得分:146)
您需要手动创建并填充IOptions<SampleOptions>
对象。您可以通过Microsoft.Extensions.Options.Options
帮助程序类完成此操作。例如:
IOptions<SampleOptions> someOptions = Options.Create<SampleOptions>(new SampleOptions());
你可以简化一下:
var someOptions = Options.Create(new SampleOptions());
显然这不是很有用。您需要实际创建并填充SampleOptions对象并将其传递给Create方法。
答案 1 :(得分:38)
如果您打算在注释中使用@TSeng指示的Mocking Framework,则需要在project.json文件中添加以下依赖项。
"Moq": "4.6.38-alpha",
恢复依赖关系后,使用MOQ框架就像创建SampleOptions类的实例一样简单,然后如上所述将其分配给Value。
以下是代码概述它的外观。
SampleOptions app = new SampleOptions(){Title="New Website Title Mocked"}; // Sample property
// Make sure you include using Moq;
var mock = new Mock<IOptions<SampleOptions>>();
// We need to set the Value of IOptions to be the SampleOptions Class
mock.Setup(ap => ap.Value).Returns(app);
设置模拟后,您现在可以将模拟对象作为
传递给构造函数SampleRepo sr = new SampleRepo(mock.Object);
HTH。
仅供参考我有一个git存储库,它在Github/patvin80
上概述了这两种方法答案 2 :(得分:12)
您可以完全避免使用MOQ。
在测试.json配置文件中使用。许多测试类文件的一个文件。在这种情况下使用ConfigurationBuilder
会很好。
appsetting.json
的示例{
"someService" {
"someProp": "someValue
}
}
设置映射类的示例:
public class SomeServiceConfiguration
{
public string SomeProp { get; set; }
}
测试所需的服务示例:
public class SomeService
{
public SomeService(IOptions<SomeServiceConfiguration> config)
{
_config = config ?? throw new ArgumentNullException(nameof(_config));
}
}
NUnit测试类:
[TestFixture]
public class SomeServiceTests
{
private IOptions<SomeServiceConfiguration> _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<SomeServiceConfiguration>());
}
[SetUp]
public void PerTestPrepare()
{
_service = new SomeService(_config);
}
}
答案 3 :(得分:7)
给出依赖于Person
的类PersonSettings
,如下所示:
public class PersonSettings
{
public string Name;
}
public class Person
{
PersonSettings _settings;
public Person(IOptions<PersonSettings> settings)
{
_settings = settings.Value;
}
public string Name => _settings.Name;
}
IOptions<PersonSettings>
可以被模拟,Person
可以如下进行测试:
[TestFixture]
public class Test
{
ServiceProvider _provider;
[OneTimeSetUp]
public void Setup()
{
var services = new ServiceCollection();
// mock PersonSettings
services.AddTransient<IOptions<PersonSettings>>(
provider => Options.Create<PersonSettings>(new PersonSettings
{
Name = "Matt"
}));
_provider = services.BuildServiceProvider();
}
[Test]
public void TestName()
{
IOptions<PersonSettings> options = _provider.GetService<IOptions<PersonSettings>>();
Assert.IsNotNull(options, "options could not be created");
Person person = new Person(options);
Assert.IsTrue(person.Name == "Matt", "person is not Matt");
}
}
要将IOptions<PersonSettings>
注入Person
而不是将其显式传递给ctor,请使用以下代码:
[TestFixture]
public class Test
{
ServiceProvider _provider;
[OneTimeSetUp]
public void Setup()
{
var services = new ServiceCollection();
services.AddTransient<IOptions<PersonSettings>>(
provider => Options.Create<PersonSettings>(new PersonSettings
{
Name = "Matt"
}));
services.AddTransient<Person>();
_provider = services.BuildServiceProvider();
}
[Test]
public void TestName()
{
Person person = _provider.GetService<Person>();
Assert.IsNotNull(person, "person could not be created");
Assert.IsTrue(person.Name == "Matt", "person is not Matt");
}
}
答案 4 :(得分:3)
这是另一种不需要Mock的简单方法,而是使用OptionsWrapper:
var myAppSettingsOptions = new MyAppSettingsOptions();
appSettingsOptions.MyObjects = new MyObject[]{new MyObject(){MyProp1 = "one", MyProp2 = "two", }};
var optionsWrapper = new OptionsWrapper<MyAppSettingsOptions>(myAppSettingsOptions );
var myClassToTest = new MyClassToTest(optionsWrapper);
答案 5 :(得分:0)
对于我的系统和集成测试,我更喜欢在测试项目中拥有配置文件的副本/链接。然后我使用ConfigurationBuilder来获取选项。
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SomeProject.Test
{
public static class TestEnvironment
{
private static object configLock = new object();
public static ServiceProvider ServiceProvider { get; private set; }
public static T GetOption<T>()
{
lock (configLock)
{
if (ServiceProvider != null) return (T)ServiceProvider.GetServices(typeof(T)).First();
var builder = new ConfigurationBuilder()
.AddJsonFile("config/appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
var configuration = builder.Build();
var services = new ServiceCollection();
services.AddOptions();
services.Configure<ProductOptions>(configuration.GetSection("Products"));
services.Configure<MonitoringOptions>(configuration.GetSection("Monitoring"));
services.Configure<WcfServiceOptions>(configuration.GetSection("Services"));
ServiceProvider = services.BuildServiceProvider();
return (T)ServiceProvider.GetServices(typeof(T)).First();
}
}
}
}
这样我就可以在TestProject里面的任何地方使用配置。对于单元测试,我更喜欢使用像patvin80描述的MOQ。
答案 6 :(得分:0)
同意Aleha的说法,使用testSettings.json配置文件可能更好。 然后,无需注入IOption,而只需将真正的SampleOptions注入类构造器中,就可以在对类进行单元测试时,在固定装置中或在测试类构造器中再次执行以下操作:
var builder = new ConfigurationBuilder()
.AddJsonFile("testSettings.json", true, true)
.AddEnvironmentVariables();
var configurationRoot = builder.Build();
configurationRoot.GetSection("SampleRepo").Bind(_sampleRepo);
答案 7 :(得分:0)
您始终可以通过Options.Create()创建选项,而不仅仅是在实际创建要测试的存储库的模拟实例之前使用AutoMocker.Use(options)。使用AutoMocker.CreateInstance <>()可以更轻松地创建实例,而无需手动传递参数
我已将您更改为SampleRepo,以便能够重现我想实现的行为。
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; }
}