Mocking WebSecurity provider

╄→гoц情女王★ 提交于 2019-12-10 18:24:44

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/15946579/mocking-websecurity-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!