Rhino Mocks supports mocking classes as well as interfaces. In fact, it can even mock classes that don't have a default constructor!
To mock a class, simply pass its type to MockRepository.CreateMock() along with any parameters for the constructor.
To create a stub on a class, use the GenerateStub() method for creating the mock.
Use this ONLY if you do not wish to set expectations on your mock. You only want to use the mock as a STUB
[Test]
public void AbuseArrayList_UsingGenerateStub()
{
ArrayList list = MockRepository.GenerateStub<ArrayList>();
// Evaluate the values from the mock
Assert.AreEqual( 0, list.Capacity );
}
Creating a mock on a class
Use the generic CreateMock<>() if you are using .Net 2.0 or higher:
[Test]
public void AbuseArrayList_UsingCreateMockGenerics()
{
MockRepository mocks = new MockRepository();
ArrayList list = mocks.CreateMock < ArrayList >();
// Setup the expectation of a call on the mock
Expect.Call( list.Capacity ).Return( 999 );
mocks.ReplayAll();
// Evaluate the values from the mock
Assert.AreEqual( 999, list.Capacity );
mocks.VerifyAll(); ;
}
Use this alternative syntax if you are using .Net 1.1:
[Test]
public void AbuseArrayList_UsingCreateMockGenerics()
{
MockRepository mocks = new MockRepository();
ArrayList list = (ArrayList) mocks.CreateMock( typeof ( ArrayList ) );
// Setup the expectation of a call on the mock
Expect.Call( list.Capacity ).Return( 999 );
mocks.ReplayAll();
// Evaluate the values from the mock
Assert.AreEqual( 999, list.Capacity );
mocks.VerifyAll(); ;
}
If you want to call the non-default constructor, just add the parameters after the type, like this:
// Non-Generics
ArrayList list = (ArrayList)mocks.CreateMock(typeof(ArrayList),500);
// With Generics
ArrayList list = mocks.CreateMock< ArrayList >( 500 );
Note: A technical limitation with mocking classes is that the creation of a mock object invokes the target class constructor, due to the mock deriving from the target class.
Up:
Rhino Mocks Documentation
Next:
Rhino Mocks - Internal Methods