zoukankan      html  css  js  c++  java
  • Moq测试基础说谈(一)——简介,下载

    Moq,就是Mock you。读音可以读成Mock~you。是Mock框架的一种。用于测试中的Mock测试。Mock是模拟的意思。Mock是模拟对象的一种技术。

    它可以用于以下情况(引用):

    ----- 真实对象具有不可确定的行为(产生不可预测的结果,如股票的行情)

    ----- 真实对象很难被创建(比如具体的web容器)

    ----- 真实对象的某些行为很难触发(比如网络错误)

    ----- 真实情况令程序的运行速度很慢

    ----- 真实对象有用户界面

    ----- 测试需要询问真实对象它是如何被调用的(比如测试可能需要验证某个回调函数是否被调用了)

    ----- 真实对象实际上并不存在(当需要和其他开发小组,或者新的硬件系统打交道的时候,这是一个普遍的问题)

     

    举个明了的例子:在开发一套BS网店系统时,想集中精力开发业务逻辑部分,而不想在数据层上花费太多时间,这时,可以通过Mock对象来模拟数据层,而不必去为数据连接,CRUDMapping等等去做太多的事,而又可以使业务测试可以进行下去。

     

    下载地址:

    http://code.google.com/p/moq/

    这里有一些文档说明。

     

    可以模拟接口和存在的类。在模拟类时有一些限制。类不能是密封的。方法要加上虚修饰符。不能模拟静态方法(可以通过适配器模式来模拟静态方法)。

    下边是一个小例子

    准备工作:

    public interface ITaxCalculator

    {

    decimal GetTax(decimal rawPrice);

    }

     

    public class Product

    {

    public int ID { get; set; }

    public String Name { get; set; }

    public decimal RawPrice { get; set; }

     

    public decimal GetPriceWithTax(ITaxCalculator calculator)

    {

    return calculator.GetTax(RawPrice) + RawPrice;

    }

    }

     

    测试

    public void TestTax()

    {

        Product myProduct = new Product { ID = 1, Name = "TV", RawPrice = 25.0M };

        Mock<ITaxCalculator> fakeTaxCalculator = new Mock<ITaxCalculator>();

        fakeTaxCalculator.Setup(tax => tax.GetTax(25.0M)).Returns(5.0M);

     

        decimal calculatedTax = myProduct.GetPriceWithTax(fakeTaxCalculator.Object);

        fakeTaxCalculator.Verify(tax => tax.GetTax(25.0M));

     

        Assert.AreEqual(calculatedTax, 30.0M); 

    }

     

    其中:

    Mock<ITaxCalculator> fakeTaxCalculator = new Mock<ITaxCalculator>();

    fakeTaxCalculator.Setup(tax => tax.GetTax(25.0M)).Returns(5.0M);

    这部分就是建立Mock对象。

    这里其实对GetTax方法进行了模拟:

    GetTax(25.0M){return 5.0M;}

     

    当调用myProduct.GetPriceWithTax(fakeTaxCalculator.Object)时,那么,

    return calculator.GetTax(RawPrice) + RawPrice;

    现在calculator对象已经进行了模拟,GetPriceWithTax返回GetTax的值+RawPrice的值。

    此时的ProductRawPrice的值为25.0M,从这个值可以得到tax.GetTax(25.0M)的值是5.0M。而25.0M+5.0M的值是30.0M。所以返回的值是30.0M。这个断言是正确的。

     

     

  • 相关阅读:
    matplotlib油漆基础
    使用ant编译项目技能
    [Recompose] Refactor React Render Props to Streaming Props with RxJS and Recompose
    [Recompose] Make Reusable React Props Streams with Lenses
    [Recompose] Compose Streams of React Props with Recompose’s compose and RxJS
    [Recompose] Create Stream Behaviors to Push Props in React Components with mapPropsStream
    [Recompose] Stream Props to React Children with RxJS
    [Recompose] Merge RxJS Button Event Streams to Build a React Counter Component
    [Recompose] Handle React Events as Streams with RxJS and Recompose
    [Recompose] Stream a React Component from an Ajax Request with RxJS
  • 原文地址:https://www.cnblogs.com/jams742003/p/1676215.html
Copyright © 2011-2022 走看看