You are here: Home / Blog / posts / Programming Magic / Mock a call to SmartServiceLocator

Mock a call to SmartServiceLocator

by jsylvest — published Sep 07, 2010 10:30 AM, last modified Jan 28, 2014 12:51 PM
Mock SmartServiceLocator<IRepository<Entity>>.GetService()

If there is a static call using SmartServiceLocator to get the repository, the repository can be mocked in the Unit Test by registering an additional service. The UCDArch Controller test base class has an override-able method to do this.

 protected override void RegisterAdditionalServices(IWindsorContainer container)
        {
            TermCodeRepository = MockRepository.GenerateStub<IRepository<TermCode>>();
            container.Kernel.AddComponentInstance<IRepository<TermCode>>(TermCodeRepository);
            base.RegisterAdditionalServices(container);
        }

The TermCodeRepository can then have the expected values assigned to it in the individual unit test like this:

            var termCodes = new List<TermCode>();
            termCodes.Add(CreateValidEntities.TermCode(1));
            termCodes[0].IsActive = true;
            termCodes[0].SetIdTo("1");
            TermCodeRepository.Expect(a => a.Queryable).Return(termCodes.AsQueryable()).Repeat.Any();

The code that calls this looks like this:

        public static TermCode GetCurrent()
        {
            var repository = SmartServiceLocator<IRepository<TermCode>>.GetService();
            var term = repository.Queryable.Where(a => a.IsActive).OrderByDescending(a => a.Id).FirstOrDefault();
            Check.Require(term != null, "Unable to find valid term.");

            return term;
        }

When:

Where:

Contact