Moles Isolation 框架是如何实现的?

How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
本文介绍了Moles Isolation 框架是如何实现的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

Moles 是微软创建的隔离框架.Moles 的一个很酷的特性是它可以模拟"静态/非虚拟方法和密封类(这在像 Moq 这样的框架中是不可能的).下面是 Moles 的快速演示:

Moles is an isolation framework created by Microsoft. A cool feature of Moles is that it can "mock" static/non-virtual methods and sealed classes (which is not possible with frameworks like Moq). Below is the quick demonstration of what Moles can do:

Assert.AreNotEqual(new DateTime(2012, 1, 1), DateTime.Now);

// MDateTime is part of Moles; the below will "override" DateTime.Now's behavior
MDateTime.NowGet = () => new DateTime(2012, 1, 1); 
Assert.AreEqual(new DateTime(2012, 1, 1), DateTime.Now);

似乎 Moles 能够在运行时修改诸如 DateTime.Now 之类的 CIL 主体.由于 Moles 不是开源的,我很想知道 Moles 使用哪种机制来在运行时修改方法的 CIL.任何人都可以解释一下吗?

Seems like Moles is able to modify the CIL body of things like DateTime.Now at runtime. Since Moles isn't open-source, I'm curious to know which mechanism Moles uses in order to modify methods' CIL at runtime. Can anyone shed any light?

推荐答案

Moles 实现了一个 CLR 分析器(特别是 ICorProfilerCallback 接口)允许在 MSIL 方法体被 .NET 运行时编译成汇编代码之前重写它们.这尤其是通过 JitCompileStarted 回调来完成的.

Moles implements a CLR profiler (in particular the ICorProfilerCallback interface) that allows to rewrite MSIL method bodies before they are compiled into assembly code by the .NET runtime. This is done in particular through the JitCompileStarted callback.

在每种方法中,Moles 都会引入如下所示的绕道:

In each method, Moles introduces a detour that looks like this:

static struct DateTime 
{
    static DateTime Now
    {
        get 
        {
            Func<DateTime> d = __Detours.GetDelegate(
                null, // this point null in static methods
                methodof(here) // current method token
                );
            if(d != null)
                return d();
            ... // original body
        }
    }
}

当你设置一个mole时,你的委托被存储在底层的__Detours字典中,每当方法被执行时就会被查找.

When you set a mole, your delegate is stored in the underlying __Detours dictionary which gets looked up whenver the method is executed.

这篇关于Moles Isolation 框架是如何实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)
Mocking Static methods using Rhino.Mocks(使用 Rhino.Mocks 模拟静态方法)