Rhino Mocks is an excellent mocking framework, but it makes simple stubbing very easy as well... I'm working on some code that has to retrieve data from AzMan services. These classes are basically just horrible wrappers around legacy COM stuff so they're not really easy to work with. Luckily, these classes all return interface types so it is easy to mock/stub.
So for one of my tests, i wanted to create an IAzApplication instance which had an IAzScopes collection with 2 IAzScope instances. The IAzScopes interface pretty much only offers an indexer property, a Count property, and the GetEnumerator method. There's also no concrete AzScopes type or something that you can create yourself for easy testing. Oh, and the IAzApplication interface defines no way of setting the IAzScopes instance to use... Joy!
Enter Rhino Mocks:
public static IAzApplication CreateAzApplicationWithTwoAzScopes(string name, string scope1, string scope2)
{
MockRepository mockRepo = new MockRepository();
IAzApplication app = mockRepo.Stub<IAzApplication>();
IAzScopes scopes = mockRepo.Stub<IAzScopes>();
var fakeScopes = new []
{
CreateAzScope(scope1, null, mockRepo),
CreateAzScope(scope2, null, mockRepo)
};
SetupResult.For(scopes.GetEnumerator()).Return(fakeScopes.GetEnumerator());
SetupResult.For(scopes.Count).Return(fakeScopes.Count());
SetupResult.For(app.Scopes).Return(scopes);
mockRepo.ReplayAll();
return app;
}
public static IAzScope CreateAzScope(string name, string description, MockRepository repo)
{
IAzScope scope = repo.Stub<IAzScope>();
scope.Description = description;
scope.Name = name;
return scope;
}
public static IAzScope CreateAzScope(string name, string description)
{
return CreateAzScope(name, description, new MockRepository());
}
This allows me to (pretty) easily create the instances i need to perform my test:
[TestMethod]
public void Map_IAzApplicationWithScopes_ReturnsApplicationWithScopes()
{
IAzApplication azApplication =
AzManEntityHelper.CreateAzApplicationWithTwoAzScopes("myApp", "scope1", "scope2");
Application application =
IAzApplicationToApplicationMapper.Map(azApplication, new AzManSidHelper(),
"domain", new MemberRepository());
Assert.IsNotNull(application.GetChildren<Scope>().FirstOrDefault(s => s.Name == "scope1"));
Assert.IsNotNull(application.GetChildren<Scope>().FirstOrDefault(s => s.Name == "scope2"));
}
Works like a charm ![]()