For mock with the return value method, Make sure to mock the objects with returned values,Mockrepository must be instantiated Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
NamespaceRhinomockproject
{
Public InterfaceIproductrepository
{
Iproduct get (IntProductid );
Ienumerable <iproduct> select ();
BoolSave (iproduct product );
}
}
Private Ienumerable <iproduct> _ fakeproducts = New List <iproduct>
{
New Product {name = " Steak " , Price = 9.85 m },
New Product {name = " Milk " , Price = 2.02 m },
New Product {name = " Diapers " , Price = 33.07 m }
};
[testmethod]
Public void teststubinterfacemethod ()
{< br> mockrepository mocks = New mockrepository ();
iproductrepository products = mocks. stub ();
Using(Mocks. Record ())
{
Setupresult. For (products. Select (). Return (_ fakeproducts );
}
VaRResults = products. Select ();
Assert. areequal (3, Results. Count ());
}
multiple mock return values [testmethod]
Public void teststubmultiplereturn ()
{< br> mockrepository mocks = New mockrepository ();
iproductrepository products = mocks. stub ();
using (mocks. record ()
{< br> setupresult
. for (products. get ( 2 )
. return ( New product {name = " beer " , price = 12.99 m });
setupresult
. for (products. get ( 12 )
. return ( New product {name = " steak " , price = 8.02 m });
}
// test
iproduct product1 = products. get ( 2 );
assert. areequal ( " beer " , product1.name);
Iproduct product2 = products. Get (12);
Assert. areequal ("Steak", Product2.name );
Iproduct product3 = products. Get (13);
Assert. isnull (product3 );
}
[Testmethod]
Public VoidTeststubignorearguments ()
{
Mockrepository mocks =NewMockrepository ();
Iproductrepository products = mocks. Stub <iproductrepository> ();
Using (Mocks. Record ())
{
Setupresult
. For (products. Get ( 1 ))
. Ignorearguments ()
. Return ( New Product {name = " Beer " , Price =12.99 m });
}
//Test
Iproduct product1 = products. Get (2);
Assert. areequal ("Beer", Product1.name );
Iproduct product2 = products. Get (12);
Assert. areequal ("Beer", Product2.name );
}
This article briefly introduces the application of the rahino mock component in TDD,CodeDownload: http://files.cnblogs.com/jackhuclan/ConsoleApplication6.rar
Complete example, see http://stephenwalther.com/archive/2008/03/23/tdd-introduction-to-rhino-mocks.aspx