gpt4 book ai didi

c# - 围绕现有实例使用 Moq 创建 Mock?

转载 作者:行者123 更新时间:2023-12-03 19:19:29 27 4
gpt4 key购买 nike

假设我们进行了广泛配置的集成测试IConfiguration .我已经将测试设置为使用 autofac 容器,现在我想使用 Mock 来替换其中一个属性的操作,而无需模拟或替换其他所有内容:

var config = MyTestContainer.Resolve<IConfiguration>();
//let's say that config.UseFeatureX = false;

//here, I'd like to create mock "around" the existing instance:
var mockedConfig = Mock.CreateWith(config); //CreateWith => a method I'd like to find how to do
mockedConfig.Setup(c => c.UseFeatureX).Returns(true);

如何围绕现有实例执行此操作?它应该类似于 .CallBase但不是仅仅调用基本实现,我希望有一种方法可以调用基本值。

最佳答案

我默认相信 Moq允许您为 IConfiguration 传递构造函数参数实现,它将为您创建该类的新实例。如果我正确理解您的问题,您宁愿使用预先构建的实例。
我假设你知道 CallBase 它并不能完全满足您的需求。

所以基本上,下面的代码片段说明了这个问题:

//suppose we've got a class:
public class A
{
public string Test {get;set;}
public virtual string ReturnTest() => Test;
}
//and some code below:
void Main()
{
var config = new A() {
Test = "TEST"
} ;

var mockedConfig = new Mock<A>(); // first we run a stock standard mock
mockedConfig.CallBase = true; // we will enable CallBase just to point out that it makes no difference
var o = mockedConfig.Object;
Console.WriteLine(o.ReturnTest()); // this will be null because Test has not been initialised from constructor
mockedConfig.Setup(c => c.ReturnTest()).Returns("mocked"); // of course if you set up your mocks - you will get the value
Console.WriteLine(o.ReturnTest()); // this will be "mocked" now, no surprises
}

现在,知道 Moq内部利用 Castle DynamicProxy它实际上允许我们为实例生成代理(他们称之为 Class proxy with target )。因此问题是 - 我们如何得到 Moq为我们制作一个。
似乎没有开箱即用的选项,并且简单地注入(inject)覆盖并不太顺利,因为库内部没有太多的控制反转,并且大多数类型和属性都标记为 internal ,使继承几乎不可能。
Castle Proxy然而,它更受用户欢迎,并且有很多公开的方法可供覆盖。所以让我们定义一个 ProxyGenerator将采用 Moq 方法的类调用并向其添加所需的功能(只需比较 CreateClassProxyWithTarget CreateClassProxy 实现 - 它们几乎相同!)

MyProxyGenerator.cs

class MyProxyGenerator : ProxyGenerator
{
object _target;

public MyProxyGenerator(object target) {
_target = target; // this is the missing piece, we'll have to pass it on to Castle proxy
}
// this method is 90% taken from the library source. I only had to tweak two lines (see below)
public override object CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, object[] constructorArguments, params IInterceptor[] interceptors)
{
if (classToProxy == null)
{
throw new ArgumentNullException("classToProxy");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
if (!classToProxy.GetTypeInfo().IsClass)
{
throw new ArgumentException("'classToProxy' must be a class", "classToProxy");
}
CheckNotGenericTypeDefinition(classToProxy, "classToProxy");
CheckNotGenericTypeDefinitions(additionalInterfacesToProxy, "additionalInterfacesToProxy");
Type proxyType = CreateClassProxyTypeWithTarget(classToProxy, additionalInterfacesToProxy, options); // these really are the two lines that matter
List<object> list = BuildArgumentListForClassProxyWithTarget(_target, options, interceptors); // these really are the two lines that matter
if (constructorArguments != null && constructorArguments.Length != 0)
{
list.AddRange(constructorArguments);
}
return CreateClassProxyInstance(proxyType, list, classToProxy, constructorArguments);
}
}

如果以上所有内容都相对简单,则实际上将其输入 Moq会有点像黑客。正如我所提到的,大多数结构都标记为 internal所以我们必须使用反射来通过:

MyMock.cs

public class MyMock<T> : Mock<T>, IDisposable where T : class
{
void PopulateFactoryReferences()
{
// Moq tries ridiculously hard to protect their internal structures - pretty much every class that could be of interest to us is marked internal
// All below code is basically serving one simple purpose = to swap a `ProxyGenerator` field on the `ProxyFactory.Instance` singleton
// all types are internal so reflection it is
// I will invite you to make this a bit cleaner by obtaining the `_generatorFieldInfo` value once and caching it for later
var moqAssembly = Assembly.Load(nameof(Moq));
var proxyFactoryType = moqAssembly.GetType("Moq.ProxyFactory");
var castleProxyFactoryType = moqAssembly.GetType("Moq.CastleProxyFactory");
var proxyFactoryInstanceProperty = proxyFactoryType.GetProperty("Instance");
_generatorFieldInfo = castleProxyFactoryType.GetField("generator", BindingFlags.NonPublic | BindingFlags.Instance);
_castleProxyFactoryInstance = proxyFactoryInstanceProperty.GetValue(null);
_originalProxyFactory = _generatorFieldInfo.GetValue(_castleProxyFactoryInstance);//save default value to restore it later
}

public MyMock(T targetInstance) {
PopulateFactoryReferences();
// this is where we do the trick!
_generatorFieldInfo.SetValue(_castleProxyFactoryInstance, new MyProxyGenerator(targetInstance));
}

private FieldInfo _generatorFieldInfo;
private object _castleProxyFactoryInstance;
private object _originalProxyFactory;

public void Dispose()
{
// you will notice I opted to implement IDisposable here.
// My goal is to ensure I restore the original value on Moq's internal static class property in case you will want to mix up this class with stock standard implementation
// there are probably other ways to ensure reference is restored reliably, but I'll leave that as another challenge for you to tackle
_generatorFieldInfo.SetValue(_castleProxyFactoryInstance, _originalProxyFactory);
}
}

鉴于我们已经完成了上述工作,实际的解决方案如下所示:

    var config = new A()
{
Test = "TEST"
};
using (var superMock = new MyMock<A>(config)) // now we can pass instances!
{
superMock.CallBase = true; // you still need this, because as far as Moq is oncerned it passes control over to CastleDynamicProxy
var o1 = superMock.Object;
Console.WriteLine(o1.ReturnTest()); // but this should return TEST
}

希望这会有所帮助。

关于c# - 围绕现有实例使用 Moq 创建 Mock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59660284/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com