代码改变世界

What is “Mock You”系列之(三):Raise,callback,verify

2010-02-21 17:15  姜 萌@cnblogs  阅读(1035)  评论(0编辑  收藏  举报

Raise

如果你说会用Setup,那么Raise就更简单了。这里注意下它是无返回值类型。

mockView.Raise(v => v.SelectionChanged += null, new OrderEventArgs { Order = new Order("moq", 500) });

Callback

Callback嘛,顾名思义就是回调。使用Callback可以使我们在某个使用特定参数匹配的方法在被调用时得到通知。比如我们要得知在一次测试中某个方法被调用了几次,可以这么做:

[TestMethod]
        public void MoqTest2()
        {
            var mo = new Mock<TargetInterfaceOne>();
            int counter = 0;
            mo.Setup(p => p.MethodPure()).Callback( () => counter++ );

            mo.Object.MethodPure();
            mo.Object.MethodPure();

            Assert.AreEqual(2, counter);
        }

在这段代码中我们在Setup方法后接了个Callback方法(或者说是调用了ISetup的Callabck方法实现)。这段代码的意思就是在调用MethodPure方法时会执行Callback中的Action委托。

调用两次MethodPure(),测试结果证明确实累加了两次counter。

Verify

有些时候我们并不关注方法的返回结果,而是关注某个方法是不是在内部被调用。

这时我们就用到了Verify/VerifyAll。同时有个有用的类型Times,规定应该调用多少次。如果验证失败则抛出异常。

[TestMethod()]

public void MoqTest3()
{
    var mo = new Mock<TargetInterfaceOne>();
    mo.Setup( p => p.MethodPure() );
    mo.Setup( p => p.MethodWithParam("123")).Verifiable("it should be invoked");
    //mo.Object.MethodPure();
    mo.Object.MethodWithParam("123");
    mo.Verify( p => p.MethodPure(), Times.AtLeastOnce() );
    mo.Verify(p => p.MethodWithParam("thto"), Times.AtLeastOnce(),
        "this method  invoking of MethodWithParam() with the parameter: \"thto\" is not happened");

    mo.Object.MethodPure();
}

如果在MethodPure前调用mo.Verify(p => p.MethodPure())则会抛出异常,因为不符合条件:在执行verify前至少调用一次。

关于Verify和VerifyAll

这两个方法会对Mock对象的所有Setup过的方法进行验证,那么有什么不同呢?注意到上面代码中绿色字体部分,有一个Verifiable方法,可以理解为为这个Setup的东西加了个验证标记。而Setup(p=>p.MethodPure())时就没有些,那么我们在使用调用Verify()时只会对MethodWithParam(“123”)进行验证而不会对MethodPure()是否被调用过进行验证。