views:

144

answers:

1

I am just starting here with mocking about, and I am trying something which I think should be quite simple.

I have a class that reads Google calendar data. First, it creates a CalendarService object, then it calls Query on that object, receives a EventFeed and iterates on the Item collection of AtomEntryCollection. I want it all to be mocked, as I don't want my tests to send any web requests around. I tried mocking it all with

var service = MockManager.Mock<CalendarService>();
var events = MockManager.MockAll<EventFeed>();
var entries = MockManager.MockAll<AtomEntryCollection>();
service.ExpectAndReturn("Query", events.MockedInstance);
events.ExpectGet("Entries", entries.MockedInstance);
entries.ExpectGetAlways("Count", 3);

but my test fails as soon as the object returned from the service.Query() method is used. I understand that in the 5th line the entries.MockedInstance was still null, so the ExpectAndReturn recorded the null as the return value - so what am I supposed to do? How can I set the mocks to return valid mock objects, instead of nulls?

Note - I am writing a .NET 2.0 project, so I can't use the Isolator features (I think). Would that have helped me? Or maybe switching to Rhino or MOQ would make it all easier?

+2  A: 

Hi Noam,

First, if you're using the old API, you should use MockObject, not Mock. Mock is for objects that are created later in the code under test, MockObject is for object that get created now.

But why use the old API? The best way I recommend, is write the tests in .Net 3.5, this way you get best of both worlds. In this case your setup looks like this:

var service = Isolate.Fake.Instance();
Isolate.WhenCalled(() => service.Query().Count).WillReturn(3);
var events = Isolate.Fake.Instance();
Isolate.WhenCalled(() => events.Entries.Count).WillReturn(3);

If however, you're hard pressed to use 2.0 no Lambda syntax, this is how it looks like:

var service = Isolate.Fake.Instance();
Isolate.WhenCalled(delegate { return service.Query().Count; }).WillReturn(3);
events = Isolate.Fake.Instance();
Isolate.WhenCalled(delegate { return events.Entries.Count; }).WillReturn(3);

Refer to this link on how to setup a VS2005 test to work with AAA API.

Thanks, I'll check it out when I get back home and mark it as the answer.
Noam Gal
The whole Isolate and AAA API only works for .NET 3/3.5. I am working on VS2008, but .NET 2.0, so I can't use it.When I replaced Mock with MockObject I got the proper objects inside my SUT, but I couldn't replace the Count property to return 3 instead of 0. I managed to fake the "Contains" method, but not other properties.What am I doing wrong? Or is there some bug with faking properties this way?
Noam Gal
Noam,Wrong. You can use the AAA for 2.0. First, you may want your tests to use 3.5 as they are separate projects than the production code. Also look at this post here:http://blog.typemock.com/2008/10/how-to-use-isolator-new-api-in-vs2005.html