I’m trying to test a bit of code that is proving to be very difficult. I would appreciate any feedback, insight, or help. Here is a simplified version of the code under test:
public class RepositoryBase<T> : RepositoryBase where T : DataContext, new()
{
protected static void Execute(Action<T> invocation)
{
using (var context = new T())
{
invocation(context);
}
}
}
public class FooRepository : RepositoryBase<FooDataContext>
{
public virtual Guid CreateFoo(string name, string description, IEnumerable<Guid> foosThingIds)
{
var id = default(Guid?);
// Call static, protected method inherited from RepositoryBase<T>.
Execute(delegate(FooDataContext context)
{
// THIS IS THE CODE I WANT TO TEST
context.CreateFoo(name, description, ref id);
// Use id and fooThingIds to make another call to the DB and other stuff
}
return id.Value;
}
}
Because I don't want to test the base repository, in my unit test, I'm creating a reflective mock of type RepositoryBase<FooDataContext>, so that I can replace the protected, static Execute method and call the Action<T> object given to it. I have this working. However, the FooDataContext object passed to this action isn't the fake one that I create in my unit test.
This is the test that I'm currently stuck on:
[Test, VerifyMocks]
public void ShouldCreateFoo()
{
Guid? expectedId = Guid.NewGuid();
const string name = "foo", description = "baz";
var dataContext = RecorderManager.CreateMockedObject<FooDataContext>();
using (var recorder = RecorderManager.StartRecording())
{
recorder.ExpectAndReturn(dataContext.CreateFoo(name, description, ref expectedId), 0);
}
var baseRepositoryMock = MockManager.MockObject<RepositoryBase<FooDataContext>>();
baseRepositoryMock.ExpectAndReturn("Execute", new DynamicReturnValue((parameters, context) =>
{
var action = parameters[0] as Action<FooDataContext>;
Assert.IsNotNull(action);
action(dataContext);
return null;
}));
var repository = new FooRepository();
var actualId = repository.CreateFoo(name, description, new List<Guid> { Guid.NewGuid() });
Assert.That(actualId, Is.EqualTo(expectedId));
}
If this isn't clear or if you need more details/info to help, please let me know.
TIA!
--
Regards,
Travis Spencer