我正在尝试为我的控制器创建一些简单的单元测试,但遇到了一个问题。
我在 MVC 4 中使用新的成员资格提供程序,并获取该WebSecurity.CurrentUserId
值并将其存储在数据库中。
当我对此进行单元测试时,它失败了,我认为我已经将其追溯到WebSecurity
根本没有被嘲笑的事实。
这是我的代码,如果它有帮助的话,
控制器
[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]
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);
}
谢谢