C# 如何使用Microsoft Fakes来模拟User.Identity.Name

C# 如何使用Microsoft Fakes来模拟User.Identity.Name,c#,unit-testing,asp.net-mvc-4,visual-studio-2012,microsoft-fakes,C#,Unit Testing,Asp.net Mvc 4,Visual Studio 2012,Microsoft Fakes,在使用Visual Studio 2012对MVC 4应用程序进行单元测试时,如何使用Microsoft Fakes模拟User.Identity.Name。 我正在为itemcreateaction方法编写单元测试 [HttpPost] public ActionResult Create([Bind(Include = "Name")]Category category) { if (categoryService.IsNameExists(categor

在使用Visual Studio 2012对MVC 4应用程序进行单元测试时,如何使用Microsoft Fakes模拟User.Identity.Name。 我正在为itemcreateaction方法编写单元测试

[HttpPost]

    public ActionResult Create([Bind(Include = "Name")]Category category)
    {

        if (categoryService.IsNameExists(category.Name))
        {
            ModelState.AddModelError("Name", "Category name already exists!");
            return View(category);
        }
        try
        {
            if (ModelState.IsValid)
            {
                UserProfile p = new UserProfile();  
                p.UserName = User.Identity.Name;

                category.CreatedBy = p;
                category.CreatedDate = DateTime.Now;
                category.Active = true;
                category.DeletedBy =  null;

                category = categoryService.SaveCategory(category);
                return RedirectToAction("Index");
            }
            return View(category);
        }
        catch (DataException dex)
        {

        }
    }


[TestMethod]
    public void Create()
    {
        Category createdCategory = new Category();
        ICategoryService service = new StubICategoryService()
        {
            SaveCategoryCategory = (category) => { return category; }
        };
        CategoryController controller = new CategoryController(service);

        using (ShimsContext.Create())
        {
            System.Fakes.ShimDateTime.NowGet = () =>
            { return new DateTime(2000, 1, 1); };

            ViewResult result = controller.Create(createdCategory) as ViewResult;

            Assert.IsNotNull(result);
        }
    }

这些是我写的动作方法和测试方法。如果有比MS Fakes更好的方法,请告诉我,(不是另一个模拟框架)。

假设您为
System.Web
System
添加了伪造参考,您可以在
中使用(ShimsContext.Create())
块执行以下操作:

var context = new System.Web.Fakes.ShimHttpContext();
var user = new StubIPrincipal
{
    IdentityGet = () =>
    {
        var identity = new StubIIdentity {NameGet = () => "foo"};
        return identity;
    }
};

context.UserGet = () => principal;
System.Web.Fakes.ShimHttpContext.CurrentGet = () => { return context; };

User
实际上是
HttpContext.User
。因此,您可以使用System.Fakes.ShimHttpContext返回整个
IPrincipal
的自定义实现,其中包含正确的标识。Name…

我最终得到了与@Sven类似的答案,但没有使用垫片,而是截取了上下文

using (AccountController controller = new AccountController())
{
    StubHttpContextBase stubHttpContext = new StubHttpContextBase();

    controller.ControllerContext = new ControllerContext(stubHttpContext, new RouteData(), controller);

    StubIPrincipal principal = new StubIPrincipal();
    principal.IdentityGet = () =>
    {
        return new StubIIdentity 
        { 
            NameGet = () => "bob" 
        };
    };
    stubHttpContext.UserGet = () => principal;
}

您可以使用GetCurrentUser方法创建一个单独的类“CustomUserContext”,而不是直接调用“User.indent.Name”。这样你就可以在测试方法中用你喜欢的任何东西来模仿CustomUserContext了。@Ledbutt也有同样的想法,但是更好的anser演示,恭喜你!最好在shim方法之外声明存根实例,这样就不会在每次get上都重新创建存根实例。在某些罕见的情况下,这可能很重要。这仍然会将用户名作为空值获取。这是调试时的值-?System.Web.HttpContext.Current.User IPrincipal存根[System.Security.Principal.Fakes.StubIPrincipal]:IPrincipal标识存根:身份存根This.HttpContext.User'((System.Web.Mvc.Controller)(This)).HttpContext“是null@Nashpaw用更新的答案更新你的问题code@SvenGrosen我需要做同样的事情,但是在为System.Web和System添加了赝品之后,我无法创建StubipPrincipal。我还试着为系统安全性制造假货,但也没有成功。知道我可能遗漏了什么吗?@mmeasor创建您自己的问题,详细说明您的设置和您所做的工作。