Here are some notes to explain what I was attempting here.
[TestClass]
public class MyTest
{
A FooBuilder will return a Qux when its Build method is called.
A FooBuilder will have getsetters for BarRepository and BazService like so:
public IBarRepository BarRepository { get; set; }
public IBazService BazService { get; set; }
The getsetters will host external dependencies
private FooBuilder fooBuilder;
[TestInitialize]
public void Setup()
{
Joel Holder wrote SessionObjectCache which wraps Session and when
used in test merely stores things in a Dictionary allowing Session to be mocked.
SessionObjectCache.Remove(CachedEntries.USER_CONTEXT);
MocksRegistry will have getsetters like so...
public Mock<IBarRepository> BarRepositoryMock { get; set; }
public Mock<IBazService> BazServiceMock { get; set; }
...that will be populated with dummy repositories and services
var registry = new MocksRegistry();
The next two lines mock methods calls that will be encountered when
the Build method on FooBuilder runs. Instead of actually running the
methods when the test runs, the methods will be monkey-patched to
return specifications based on the these two lines of code.
registry.BarRepositoryMock.Setup(repo =>
repo.GetAll()).Returns(new List<Bar>().AsQueryable());
registry.BazServiceMock.Setup(repo =>
repo.DoesMatchAnyBazForBars(It.IsAny<List<Bar>>()));
Let's instantiate our FooBuilder while telling it how to conditional
behave so as not to really need external dependencies.
fooBuilder = new FooBuilder
{
BarRepository = registry.BarRepositoryMock.Object,
BazService = registry.BazServiceMock.Object
};
var testServices = new Dictionary<string, object>();
testServices[AppCtxIds.FOO_BUILDER] = fooBuilder;
Here we are monkey-patching ServiceLocator so that when an IoC
attempt to wire up IBarRepository to an BarRepository occurs the
true ServiceLocator will be sidestepped in favor of our fake one.
ServiceLocator.LookupSource = () => testServices;
}
In our test we will test the Qux of a UserContext. In the name of
making a Qux will must deal with two calls to external dependencies.
We are dealing with the dependencies by way of mocking.
[TestMethod]
public void LetsTest()
{
var qux = BuildQux("Tom");
var userContext = SessionObjectCache.LazyGet<UserContext>
(CachedEntries.USER_CONTEXT,
new Func<UserContext>(() =>
{
return new UserContext { Qux = qux };
}));
Assert.IsTrue(SessionObjectCache.Exists(CachedEntries.USER_CONTEXT));
Assert.AreEqual("Tom", SessionObjectCache.Get<UserContext>
(CachedEntries.USER_CONTEXT).Qux.Name);
}
private Qux BuildQux(string whatever)
{
return fooBuilder.Build(whatever);
}
private class TestController : Controller
{
}
}
No comments:
Post a Comment