假设我们有大量配置的集成测试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);
Run Code Online (Sandbox Code Playgroud)
如何围绕现有实例进行这种包装?它应该类似于.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
}
Run Code Online (Sandbox Code Playgroud)
现在,知道Moq内部利用了Castle DynamicProxy,它实际上允许我们为实例生成代理(他们将其称为带有 target 的类代理)。因此问题是——我们如何Moq为我们制作一个。似乎没有这样的开箱即用选项,并且简单地注入覆盖并不太顺利,因为库内没有太多控制反转,并且大多数类型和属性都标记为internal,使得继承几乎不可能。
Castle Proxy然而,它对用户更加友好,并且有很多公开的方法可供重写。因此,让我们定义一个ProxyGenerator类,它将接受方法Moq调用并向其添加所需的功能(只需比较CreateClassProxyWithTarget和CreateClassProxy实现 - 它们几乎相同!)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果上述所有内容都相对简单,那么实际上将其输入Moq将有点困难。正如我所提到的,大多数结构都已标记internal,因此我们必须使用反射来获取:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
鉴于我们已经完成了上述工作,实际的解决方案将如下所示:
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
}
Run Code Online (Sandbox Code Playgroud)
希望这有帮助。
| 归档时间: |
|
| 查看次数: |
1601 次 |
| 最近记录: |