Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Rob Carlaw 21 posts 134 karma points
    May 15, 2017 @ 11:16
    Rob Carlaw
    0

    Unit Testing custom controller - Members property always null.

    Hi,

    I have a controller like:

        public class ShoppingCartController : RenderMvcController
    {
        public override ActionResult Index(RenderModel model)
        {
            ShoppingCartViewModel vm = new  ShoppingCartViewModel(model.Content);
    
            var member = Members.GetCurrentMember();
            if (member == null)
            {
                vm.ShowNotLoggedInMessage = true;
                return View(vm);
            }
    
            Guid customerGuid;
            Guid.TryParse(member.GetProperty("customerGuid")?.Value.ToString(), out customerGuid);
    
            if (customerGuid == Guid.Empty)
            {
                vm.ShowNoCartItemsMessage = true;
                return View(vm);
            }
    

    Now when I'm writing tests I set the application context like *I found this on a blog

    var applicationContext = new ApplicationContext( CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()) ); UmbracoContext.EnsureContext( Mock.Of<HttpContextBase>(), applicationContext, new WebSecurity(Mock.Of<HttpContextBase>(), applicationContext), Mock.Of<IUmbracoSettingsSection>(), Enumerable.Empty<IUrlProvider>(), true );

    which runs before my test.

            [Test]
        public void ItShouldReturnNotLoggedInError()
        {
            ShoppingCartController controller = new ShoppingCartController();
    
            var result = controller.Index(..... )
    

    It blows up because Members is null. I'm guessing I need to set it up on the Context or something but I'm struggling.

    I can see the base class of RenderMVCController UmbracoHelper is passed into the controller constructor. I can't for the life of me get Members to not be null. I could stub it out by wrapping a interface around it but then I'm adding another layer. I also don't want to add a new constructor just for unit testing.

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies