Expect.Call Return

160 views
Skip to first unread message

Spas

unread,
Mar 13, 2009, 6:27:13 AM3/13/09
to Rhino.Mocks
Hi guys

New to this google group, and new to Rhino Mocks.

I can't understand how this works. I want to unit test a method, that
uses another class to access a database. Naturally I do not want my
unit test to access the database, so I want to mock that other class.

My test method:

/// <summary>
///A test for GetDefinitions
///</summary>
[TestMethod]
public void GetDefinitionsTest()
{
string[] names = {"name1", "name2"};
const bool includeReferencedDefinitions = false;
var expected = new List<DataExportDefinition>
{
new
DataExportDefinition
{Name =
"name1", Type = "type1", Data = "data1"},
new
DataExportDefinition
{Name =
"name2", Type = "type2", Data = "data2"}
};

var mockDbHandler =
MockRepository.GenerateMock<DataExportDefinitionDatabaseHandler>();
var mockDataExportDefinitionExporter =
MockRepository.GenerateMock<DataExportDefinitionExporter>();

Expect.Call(mockDbHandler.GetDataExportDefinition(expected
[0].Name)).Return(expected[0]);
Expect.Call(mockDbHandler.GetDataExportDefinition(expected
[1].Name)).Return(expected[1]);

var actual =
mockDataExportDefinitionExporter.GetDefinitions(names,
includeReferencedDefinitions, mockDbHandler);

mockDataExportDefinitionExporter.VerifyAllExpectations();

Assert.AreEqual(expected[0].Name, actual[0].Name);
Assert.AreEqual(expected[0].Type, actual[0].Type);
Assert.AreEqual(expected[0].Data, actual[0].Data);
Assert.AreEqual(expected[1].Name, actual[1].Name);
Assert.AreEqual(expected[1].Type, actual[1].Type);
Assert.AreEqual(expected[1].Data, actual[1].Data);
}


I thought this would work, but when this line is reached:
Expect.Call(mockDbHandler.GetDataExportDefinition(expected
[0].Name)).Return(expected[0]);
- the actual GetDataExportDefinition method is called. I expected that
the mocking object would just return whatever I gave as the return
value to the Return method - and NOT run the actual method. How do I
get this behaviour?

When running this unit test I get an error related to the
GetDataExportDefinition method, that it cannot connect to the database
(which is fine for this test, because I do NOT want it to run this
method).

Hope I made myself clear, and hope to find some friendly people with
some ideas to help me here :)

Thanks in advance
/Spas

Shawn Neal

unread,
Mar 13, 2009, 11:53:52 AM3/13/09
to Rhino...@googlegroups.com
What you found is correct, the base class method gets called.  That confuses a lot of people.  Save yourself some grief and an extract an interface from DataExportDefinitionDatabaseHandler and mock/stub the interface instead.  You'll find that much easier.

Søren Pedersen

unread,
Mar 13, 2009, 5:34:41 PM3/13/09
to Rhino...@googlegroups.com
Hi Shawn
 
Thanks a lot!
I will give your suggestion a go.
 
/Spas

Reply all
Reply to author
Forward
0 new messages