现在的位置: 首页 > 综合 > 正文

RhinoMock入门(4)——次序和委托

2013年02月14日 ⁄ 综合 ⁄ 共 2623字 ⁄ 字号 评论关闭

(一)次序(Ordered

rhinomock中,可以按次序调用方法。默认条件下,方法调用没有顺序。如果按次序录制,那么在调用方法时必须按录制时相同的次序进行。

 

请看:

public interface ICustomer
{
   string ShowTitle(string str);
   int Unid { getset; }
   string CustomerName { getset; }
   string Address { getset; }
}

 

测试:

public void TestNoOrder()
{
    MockRepository mocks 
= new MockRepository(); 
    ICustomer customer 
= mocks.StrictMock<ICustomer>(); 

    //默认条件下是没顺序的
    Expect.Call(customer.Unid).Return(1);
    Expect.Call(customer.CustomerName).Return(
"宋江");
    Expect.Call(customer.Address).Return(
"山东"); 

    mocks.ReplayAll(); 

    Assert.AreEqual("宋江", customer.CustomerName);
    Assert.AreEqual(
1, customer.Unid);
    Assert.AreEqual(
"山东", customer.Address);
}

 

 

当使用次序时:

public void TestOrder()
{
    MockRepository mocks 
= new MockRepository(); 
    ICustomer customer 
= mocks.StrictMock<ICustomer>();
    
using (mocks.Ordered())
    {
        Expect.Call(customer.Unid).Return(
1);
        Expect.Call(customer.CustomerName).Return(
"宋江");
        Expect.Call(customer.Address).Return(
"山东");
    } 

    mocks.ReplayAll();

    Assert.AreEqual("宋江", customer.CustomerName);
    Assert.AreEqual(
1, customer.Unid);
    Assert.AreEqual(
"山东", customer.Address);
}

 

这时,如果调用时没有按期望时的次序进行,那就会出错,抛出异常。

这种次序可以灵活使用,例如可以次序一个mock,然后期望条件达到后,再不按次序进行。注意:在进行回播前要退出次序。

 

(二)模拟委托

先定义委托:

public delegate void DoThing(string strMsg);

  

然后模拟委托:

[Test]
public void TestDelegate1()
{
    MockRepository mocks 
= new MockRepository();
    var oo 
= mocks.DynamicMock<DoThing>();
    oo(
"");
    mocks.ReplayAll();
    oo(
"");
    mocks.VerifyAll();
}

 

有两个系统定义的委托Func<TResult>Action<T>

前是带返回值的委托,后者不带返回值,现在通过Action<T>来实现上例

[Test]
public void TestDelegate2()
{
    MockRepository mocks 
= new MockRepository();
    var oo 
= mocks.DynamicMock<Action<string>>();

    oo("");
    mocks.ReplayAll();
    oo(
"");
    mocks.VerifyAll();
}

 

再来一个Func,即带返回值的委托的例子:

[Test]
public void TestDelegateFunc()
{
    MockRepository mocks 
= new MockRepository();
    var oo 
= mocks.DynamicMock<Func<stringstring>>();

    Expect.Call(oo("")).Return("abc");
    mocks.ReplayAll();
    Assert.AreEqual(
"abc", oo(""));
}

 

 

再来一个例子:

public class Customer
{
     Func
<stringstring> _fun;
     
public Customer(Func<stringstring> fun)
     {
          _fun 
= fun;
     }

     public void DoSomething(string strMsg)
     {
          Console.WriteLine(_fun(strMsg));
     }
}

 

 

测试:

[Test]
public void TestDelegateFunc()
{
    MockRepository mocks 
= new MockRepository();
    var oo 
= mocks.DynamicMock<Func<stringstring>>();
    Expect.Call(oo(
"")).Return("abc");
    mocks.ReplayAll(); 

    var customer = new Customer(oo);
    customer.DoSomething(
"");
}

 

于对这两种委托请见:http://www.cnblogs.com/jams742003/archive/2009/10/31/1593393.html

 

 

抱歉!评论已关闭.