web-dev-qa-db-ja.com

.Net Core Unit Testing-モックIOptions <T>

ここで本当に明白な何かを見逃しているように感じます。 .Net Core IOptions pattern(?)を使用してオプションを注入する必要があるクラスがあります。そのクラスの単体テストに行くとき、クラスの機能を検証するオプションのさまざまなバージョンをモックしたいと思います。 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);
        }
    }
}
84
Matt

IOptions<SampleOptions>オブジェクトを手動で作成して設定する必要があります。これは、Microsoft.Extensions.Options.Optionsヘルパークラスを介して行うことができます。例えば:

IOptions<SampleOptions> someOptions = Options.Create<SampleOptions>(new SampleOptions());

あなたはそれを少し単純化することができます:

var someOptions = Options.Create(new SampleOptions());

明らかに、これはそのままではあまり役に立ちません。実際にSampleOptionsオブジェクトを作成して値を設定し、Createメソッドに渡す必要があります。

151
Necoras

コメントの@TSengで示されているようにモッキングフレームワークを使用する場合は、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。

参考までに、 Github/patvin8 でこれら2つのアプローチを概説するgitリポジトリがあります

39
patvin80

MOQの使用をまったく避けることができます。テストの.json構成ファイルで使用します。多くのテストクラスファイル用の1つのファイル。この場合は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);
    }
}
12
aleha

次のように、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>を明示的にctorに渡す代わりにPersonに注入するには、次のコードを使用します。

[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");
    }
}
8
Frank Rem

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);
4
Robert Corvus

TestSettings.json構成ファイルを使用する方がおそらく良いとAlehaに同意します。そして、IOptionを挿入する代わりに、クラスコンストラクターに実際のSampleOptionsを単純に挿入できます。クラスを単体テストする場合、フィクスチャーまたはテストクラスコンストラクターで次の操作を実行できます。

   var builder = new ConfigurationBuilder()
  .AddJsonFile("testSettings.json", true, true)
  .AddEnvironmentVariables();

  var configurationRoot = builder.Build();
  configurationRoot.GetSection("SampleRepo").Bind(_sampleRepo);
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を使用することを好みます。

0
Mithrandir

オプションを作成するには、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; }
}
0
matei