Buu*_*yen 22 .net c# mocking isolation-frameworks moles
Moles是Microsoft创建的隔离框架.Moles的一个很酷的功能是它可以"模拟"静态/非虚拟方法和密封类(这对于像Moq这样的框架是不可能的).以下是Moles可以做的快速演示:
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.谁能摆脱任何光明?
Pel*_*eli 49
Moles实现了一个CLR分析器(特别是ICorProfilerCallback接口),它允许在.NET运行时将MSIL方法体编译成汇编代码之前重写它们.这通过JitCompileStarted回调特别完成.
在每种方法中,Moles引入了一个如下所示的绕道:
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字典中,该字典在执行方法时会被查找.
| 归档时间: | 
 | 
| 查看次数: | 3259 次 | 
| 最近记录: |