Skip to content

Instantly share code, notes, and snippets.

@paulbatum
Forked from skoon/MostlyScottish.cs
Created May 27, 2011 05:16
Show Gist options
  • Save paulbatum/994682 to your computer and use it in GitHub Desktop.
Save paulbatum/994682 to your computer and use it in GitHub Desktop.
Hand rolled mocks work fine, I don't get it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterfaceInheritanceMocking
{
class Program
{
static void Main(string[] args)
{
var mock = new HandRolledMock();
var doer = new StuffDoer(mock);
doer.MethodUnderTest();
Console.ReadLine();
}
}
public class HandRolledMock : IStuffRepository
{
public void Save(Stuff entity)
{
Console.WriteLine("I'm in your repository mocking ur Save");
}
}
//So this is what we have now.
public interface IRepository<T>
{
void Save(T entity);
}
public interface IStuffRepository : IRepository<Stuff>
{
}
public abstract class BaseRepository<T> : IRepository<T>
{
public void Save(T entity)
{
//method that accepts string,Func<ISession,T>
}
}
public class StuffRepository : BaseRepository<Stuff>, IStuffRepository
{
//Trying to use NSubstitute to mock the "Save" method, but where is it really at runtime?
}
public class Stuff
{
//poco DB entity class
}
public class StuffDoer
{
private readonly IStuffRepository _StuffRepo;
public StuffDoer(IStuffRepository stuffRepo)
{
_StuffRepo = stuffRepo;
}
public void MethodUnderTest()
{
// blah blah blah, stuff we can't mock because they are all private instance methods
IEnumerable<Stuff> stuffCollection = new List<Stuff>(new[] { new Stuff() });
foreach (var thing in stuffCollection)
{
_StuffRepo.Save(thing);
//Where is the Save method located at runtime and what can we really mock at this point?
//I think it's really located in BaseRepository BUT my magic mocker thinks that it is located on the instance of
//StuffRepository. So when it mocks "Save" on the StuffRepository, the mock method is located at one place on
//the heap, and the real Save method on the BaseRepository is located at another location on the heap. Both the
//StuffRepository and BaseRepository have their own MethodTables.
}
}
}
}
@skoon
Copy link

skoon commented May 27, 2011

hmmm, so the "Save" method is actually declared on the IRepository interface and implemented in the ABC BaseRepository. So when I tried the hand-rolled mock, I made the save method an override.

@paulbatum
Copy link
Author

I might be missing something but... what is there to override? Your hand-rolled mock is implementing an interface and doesn't inherit from anything else. You can't override from your hand-rolled mock.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment