Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 437
Andrew Davis Avatar asked Mar 03 '26 02:03

Andrew Davis


1 Answers

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.

like image 105
aquaraga Avatar answered Mar 05 '26 04:03

aquaraga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!