0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

IOptionsSnapshotを生み出す

Posted at

コンストラクタの引数にIOptionsSnapshot<TOptions>を保有するクラスがあるとします。

MyApp.cs
public class MyApp
{
    private readonly IOptionsSnapshot<MySettings> mySettings;

    public MyApp(IOptionsSnapshot<MySettings> settings)
    {
        this.mySettings = settings;
    }

    public void DoSomething()
    {
        Console.WriteLine(this.mySettings.Value.Name);
    }
}

このクラスのテストコードを記述するとなった場合、MyAppクラスに渡すために何らかの方法でテスト用のIOptionsSnapshot<TOptions>を生み出す必要があります。
以下の例ではモック用のライブラリであるMoqを使ってIOptionsSnapshot<TOptions>を生成しています。

IOptionsSnapshotのモック生成例
var myOptionsMock = new Mock<IOptionsSnapshot<MySettings>>();
myOptionsMock
    .Setup(o => o.Value)
    .Returns(new MySettings
    {
        Name = "test",
    });
var app = new MyApp(myOptionsMock.Object);

この方法では、IOptionsSnapshot<TOptions>を生み出すためにモックを定義する必要があります。
今回はモックを定義したくなかったのでIOptionsSnapshot<TOptions>を自力生成する方法を試そうと思います。
そのために、以下の2つのクラスを予め作成します。

OptionsSnapshot.cs
public static class OptionsSnapshot
{
    public static IOptionsSnapshot<TOptions> Create<TOptions>(TOptions options) where TOptions : class, new()
    {
        return new OptionsSnapshotWrapper<TOptions>(options);
    }
}
OptionsSnapshotWrapper.cs
public class OptionsSnapshotWrapper<TOptions> : IOptionsSnapshot<TOptions> where TOptions : class, new()
{
    public TOptions Value { get; }

    public OptionsSnapshotWrapper(TOptions options)
    {
        Value = options;
    }

    public TOptions Get(string name)
    {
        // 一旦これで
        throw new NotImplementedException();
    }
}

これらのクラスを用いて、IOptionsSnapshot<TOptions>を生成するコードは以下のように書けます。

var myOptions = OptionsSnapshot.Create(new MySettings
{
    Name = "test"
});
var app = new MyApp(myOptions);

まとめ

IOptionsSnapshot<TOptions>を生み出せた。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?