Mocking WebSecurity Provider

I am trying to create some simple unit tests for my controllers, and I ran into a problem.

I use the new MVC 4 membership provider and get WebSecurity.CurrentUserId and WebSecurity.CurrentUserId this value in the database.

When I run my unit tests against this, it fails, and I think I am tracking it again, that WebSecurity is not mocking at all.

Here is my code, if it helps at all,

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); } 

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

+3
source share
1 answer

A possible solution is to create a wrapper class around WebSecurity - say WebSecurityWrapper . Set static WebSecurity methods, such as WebSecurity.CurrentUserId , as instance methods on the wrapper. The wrapper task in this case will simply delegate all WebSecurity calls.

Paste WebSecurityWrapper into the GroupController constructor. Now you can muffle the shell using the mocking structure of your choice, and thus check the logic of the controller.

Hope this helps.

+4
source

Source: https://habr.com/ru/post/1486118/


All Articles