Andrew Davis
Andrew Davis

Reputation: 470

Mocking WebSecurity provider

I'm trying to create some simple unit tests for my controllers and I've come across an issue.

I'm using the new membership provider in MVC 4 and getting the WebSecurity.CurrentUserId and storing that value in the database.

When I run my unit tests against this it's failing and I think I have track this back to the fact that the WebSecurity isn't being mocked at all.

Here's my code if it helps at all,

The Controller

    [HttpPost]
    public ActionResult Create(CreateOrganisationViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            Group group = _groupService.Create(
                new Group
                {
                    Name = viewModel.Name,
                    Slug = viewModel.Name.ToSlug(),
                    Profile = new Profile
                    {
                        Country = viewModel.SelectedCountry,
                        Description = viewModel.Description
                    },
                    CreatedById = WebSecurity.CurrentUserId,
                    WhenCreated = DateTime.UtcNow,
                    Administrators = new List<User> {_userService.SelectById(WebSecurity.CurrentUserId)}
                });
            RedirectToAction("Index", new {id = group.Slug});
        }
        return View(viewModel);
    }

The Test

    [Test]
    public void SuccessfulCreatePost()
    {
        CreateOrganisationViewModel createOrganisationViewModel = new CreateOrganisationViewModel
        {
            Description = "My Group, bla bla bla",
            Name = "My Group",
            SelectedCountry = "gb"
        };

        IUserService userService = MockRepository.GenerateMock<IUserService>();
        IGroupService groupService = MockRepository.GenerateMock<IGroupService>();
        groupService.Stub(gS => gS.Create(null)).Return(new Group {Id = 1});
        GroupController controller = new GroupController(groupService, userService);
        RedirectResult result = controller.Create(createOrganisationViewModel) as RedirectResult;
        Assert.AreEqual("Index/my-group", result.Url);
    }

Thanks

Upvotes: 3

Views: 1307

Answers (1)

aquaraga
aquaraga

Reputation: 4168

A possible solution is to create a wrapper class around WebSecurity - say WebSecurityWrapper. Expose the static WebSecurity methods such as WebSecurity.CurrentUserId as instance methods on the wrapper. The wrapper's job in this case would be simply to delegate all the calls to WebSecurity.

Inject WebSecurityWrapper into the GroupController's constructor. Now, you can stub the wrapper using the mocking framework of your choice - and thus test the controller logic.

Hope this helps.

Upvotes: 4

Related Questions