与嘲讽起订量扩展方法 [英] Mocking Extension Methods with Moq
问题描述
我有一个preexisting接口...
I have a preexisting Interface...
public interface ISomeInterface
{
void SomeMethod();
}
和我使用一个混合扩展了这一intreface ...
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()
我的问题是,有没有模拟出的混入调用一个不错的方式?
My question is, is there a nice way to mock out the mixin call?
推荐答案
您不能直接模拟静态方法(因此扩展方法)与嘲讽框架。您可以尝试痣( http://research.microsoft.com/en-美国/项目/ PEX / downloads.aspx ),来自微软的免费工具,它实现了不同的方法。
这里是该工具的说明:
You can't "directly" mock static method (hence extension method) with mocking framework. You can try Moles (http://research.microsoft.com/en-us/projects/pex/downloads.aspx), a free tool from Microsoft that implements a different approach. Here is the description of the tool:
痣是在.NET测试存根和弯路是基于一个代表轻量级框架。
Moles is a lightweight framework for test stubs and detours in .NET that is based on delegates.
摩尔数可用于绕任何.NET方法,包括在密封类型的非虚拟/静态方法
Moles may be used to detour any .NET method, including non-virtual/static methods in sealed types.
您可以使用痣任何测试框架(它是独立的事情)。
You can use Moles with any testing framework (it's independent about that).
这篇关于与嘲讽起订量扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!