Sunday, June 22, 2014

mixing StructureMap with NSubstitute

I am looking at an app where the core has its external dependencies hydrated by StructureMap when the application spins up. In testing, they are supplied a different way and the methods on the interfaces corresponding to external dependencies are easily mocked with NSubstitute in C# in individual test classes by doing dot syntax off of dependencies (interfaces) in protected fields on a common base class that the test classes inherit from. The base class looks like this:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;
using StructureMap;
namespace Whatever
{
   [TestClass]
   public class CommonBaseForTests
   {
      protected IFooDependency FooDependency;
      protected IBarDependency BarDependency;
      
      [TestInitialize()]
      public void NSubstituteBaseControllerTestInitialise()
      {
         ObjectFactory.Initialize(x => x.AddRegistry(new WireUpMagic()));
         FooDependency = ObjectFactory.GetInstance<IFooDependency>();
         BarDependency = ObjectFactory.GetInstance<IBarDependency>();
      }
   }
}

 
 

What I am calling WireUpMagic has a better name in the app I am looking at. I don't really understand it yet. It inherits from Registry which sits in the StructureMap.Configuration.DSL namespace. It looks like so:

using StructureMap.Configuration.DSL;
using NSubstitute;
namespace Whatever
{
   public class WireUpMagic : Registry
   {
      public WireUpMagic()
      {
         var foo = Substitute.For<IFooDependency>();
         var bar = Substitute.For<IBarDependency>();
         For<IFooDependency>().Use(foo);
         For<IBarDependency>().Use(bar);
      }
   }
}

No comments:

Post a Comment