本文介绍了使用 Moq 模拟扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个预先存在的界面...

I have a preexisting Interface...

public interface ISomeInterface
{
    void SomeMethod();
}

我已经使用 mixin 扩展了这个接口...

and I've extended this intreface using a mixin...

public static class SomeInterfaceExtensions
{
    public static void AnotherMethod(this ISomeInterface someInterface)
    {
        // Implementation here
    }
}

我有一个班级正在调用它,我想测试它...

I have a class thats calling this which I want to test...

public class Caller
{
    private readonly ISomeInterface someInterface;

    public Caller(ISomeInterface someInterface)
    {
        this.someInterface = someInterface;
    }

    public void Main()
    {
        someInterface.AnotherMethod();
    }
}

还有一个测试,我想模拟接口并验证对扩展方法的调用......

and a test where I'd like to mock the interface and verify the call to the extension method...

    [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();
    }

但是运行这个测试会产生一个异常...

Running this test however generates an exception...

System.ArgumentException: Invalid setup on a non-member method:
x => x.AnotherMethod()

我的问题是,有没有一种很好的方法来模拟 mixin 调用?

My question is, is there a nice way to mock out the mixin call?

推荐答案

我使用了 Wrapper 来解决这个问题.创建一个包装对象并传递您的模拟方法.

I have used a Wrapper to get around this problem. Create a wrapper object and pass your mocked method.

请参阅模拟单元测试的静态方法 作者 Paul Irwin,它有很好的例子.

See Mocking Static Methods for Unit Testing by Paul Irwin, it has nice examples.

这篇关于使用 Moq 模拟扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 19:08