Moq を使用して拡張メソッドをシミュレートする: Mixin 呼び出しをカプセル化する
拡張メソッドに依存するクラスをテストする場合、Moq を使用してこれらのメソッドをモックするのは簡単ではありません。この記事では、この問題を解決し、ラッパー オブジェクトを使用した解決策を提供します。
次のコードを考えてみましょう。ここでは、インターフェイスがミックスインを使用して拡張され、クラスがこの拡張メソッドを呼び出します。
public interface ISomeInterface { void SomeMethod(); } public static class SomeInterfaceExtensions { public static void AnotherMethod(this ISomeInterface someInterface) { // 实现代码 } } public class Caller { private readonly ISomeInterface someInterface; public Caller(ISomeInterface someInterface) { this.someInterface = someInterface; } public void Main() { someInterface.AnotherMethod(); } }
[Test] public void Main_BasicCall_CallsAnotherMethod() { // Arrange var someInterfaceMock = new Mock<ISomeInterface>(); someInterfaceMock.Setup(x => x.AnotherMethod()).Verifiable(); // 此处会报错 var caller = new Caller(someInterfaceMock.Object); // Act caller.Main(); // Assert someInterfaceMock.Verify(); }
この問題を解決するには、ラッパー オブジェクトを作成してミックスイン呼び出しをカプセル化します。これにより、拡張メソッドの代わりにラッパー メソッドをモックできるようになります。
例:
public class SomeInterfaceWrapper { private readonly ISomeInterface someInterface; public SomeInterfaceWrapper(ISomeInterface someInterface) { this.someInterface = someInterface; } public void AnotherMethod() { someInterface.AnotherMethod(); } }
[Test] public void Main_BasicCall_CallsAnotherMethod() { // Arrange var wrapperMock = new Mock<SomeInterfaceWrapper>(); wrapperMock.Setup(x => x.AnotherMethod()).Verifiable(); var caller = new Caller(new SomeInterfaceWrapper(wrapperMock.Object)); // 注意此处修改 // Act caller.Main(); // Assert wrapperMock.Verify(); }
以上がMoq を使用して拡張メソッドをモックするにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。