Search code examples
c#unit-testingmoqautofacservice-locator

Moq Service Locator for unit test


I am trying to figure this out but no success. how can I mock ProcessorLocator for these two tests?

Here is my ServiceLocator:

public class ProcessorLocator : IProcessorLocator
{
    public static IContainer Container;

    T IProcessorLocator.GetProcessor<T>()
    {
        return Container.Resolve<T>();
    }

    public static IServiceProvider Init(IServiceCollection services)
    {
        //Autofac
        var containerBuilder = new ContainerBuilder();
        containerBuilder.RegisterModule<ProcessorRegistrationModule>();
        containerBuilder.RegisterType<ProcessorLocator>().As<IProcessorLocator>();
        containerBuilder.Populate(services);
        Container = containerBuilder.Build();

        return Container.Resolve<IServiceProvider>();
    }

    public class ProcessorRegistrationModule : Autofac.Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            Assembly asm = typeof(ProcessorLocator).GetTypeInfo().Assembly;

            builder.RegisterAssemblyTypes(asm)
                .Where(t => t.Name.EndsWith("Processor"))
                .As(t => t.GetInterfaces().FirstOrDefault(
                    i => i.Name == "I" + t.Name));

            builder.RegisterAssemblyTypes(asm)
                .Where(t => t.Name.EndsWith("Repository"))
                .As(t => t.GetInterfaces().FirstOrDefault(
                    i => i.Name == "I" + t.Name));
        }
    }
}

Here is my class under test:

public class MainNavigationViewComponent : ViewComponent
{
    public IProcessorLocator _ProcessorLocator { get; set; }

    public MainNavigationViewComponent(IProcessorLocator processorLocator)
    {
        _ProcessorLocator = processorLocator;
    }       

    public IViewComponentResult Invoke()
    {
        IMenuItemRepository _menuItemRepository = _ProcessorLocator.GetProcessor<IMenuItemRepository>();

        IEnumerable<Entity.MenuItem> _menuItemList = _menuItemRepository.GetAll().Where(x => x.Parent == null && x.onMenu == true);

        return View(_menuItemList.ToList());
    }
}

My attempts:

[Fact]
public void ActualTest()
{
    //var mockS = new Mock<IProcessorLocator>();
    //ProcessorLocator.Container.SetLocatorProvider(() => mockS.Object);
    var container = BL.ProcessorLocator.InitTest();
    _menuItemMock.Setup(x => x.GetAll()).Returns(new List<MenuItem>() { new MenuItem() { Text = "uu"}, new MenuItem() { Text = "zz" } });

    IMenuItemRepository _menuItemRepository = container.Resolve<IMenuItemRepository>();

     IEnumerable<Entity.MenuItem> _menuItemList = _menuItemRepository.GetAll().Where(x => x.Parent == null && x.onMenu == true);
}

[Fact]
public void MainNavigationViewComponent Test()
{
        //var _subject = new MainNavigationViewComponent(_menuItemMock.Object)
        //{
        //    ActionContext = new ActionContext()
        //    {
        //        HttpContext = new DefaultHttpContext()
        //    }
        //};
}

Solution

  • Based on the code you've provided:

    var fakeMenuRepository = new Mock<IMenuItemRepository>();
    fakeMenuRepository.Setup(repository => repository.GetAll())
                      .Returns(new List<MenuItem>()
                      {
                          new MenuItem() { Text = "uu" },
                          new MenuItem() { Text = "zz" }
                      });
    var fakeLocator = new Mock<IProcessorLocator>();
    fakeLocator.Setup(locator => locator.GetProcessor<IMenuItemRepository>())
               .Returns(fakeMenuRepository.Object);
    
    var target = new MainNavigationViewComponent(fakeLocator.Object);
    

    Another option is to use a real container and than override the instance of IMenuItemRepository; as I explained in this answer