首页 > 其他 > 详细

What is “Mock You” :Raise,callback,verify [转载]

时间:2014-02-19 03:40:13      阅读:432      评论:0      收藏:0      [点我收藏+]

http://www.cnblogs.com/wJiang/archive/2010/02/21/1670637.html

 

 

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()是否被调用过进行验证。

What is “Mock You” :Raise,callback,verify [转载]

原文:http://www.cnblogs.com/zcm123/p/3554339.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!