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

时间:2014-05-02 12:56:36

标签: c# unit-testing asp.net-mvc-4 visual-studio-2012 microsoft-fakes

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

[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之外还有更好的方法可以做到这一点,请告诉我,(不是另一个模拟框架)。

3 个答案:

答案 0 :(得分:1)

假设您已为System.WebSystem添加了Fakes引用,您可以在using (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; };

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我最终得到了与@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;
}