如何使用微软正版正货嘲笑User.Identity.Name [英] How can use Microsoft Fakes to mock User.Identity.Name

查看:186
本文介绍了如何使用微软正版正货嘲笑User.Identity.Name的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用微软正版正货嘲笑User.Identity.Name时,单元测试MVC 4应用程序使用Visual Studio 2012。
我在写单元测试项目创建的操作方法。

How can I use Microsoft Fakes to mock User.Identity.Name when unit testing MVC 4 application with Visual Studio 2012. I'm writing unit test for item create action method.

[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正版正货要做到这一点其他的,请告诉我,(不是另一个嘲弄框架)。

These are the action method and test method I have written. If there is better way to do this other than MS Fakes please tell me, (not another mocking framework).

推荐答案

假设你已经添加了正版正货参考的System.Web 系统,你可以做这样的事情里面你的使用(ShimsContext.Create())块:

Assuming you've added Fakes references for System.Web and System, you can do something like this inside your using (ShimsContext.Create()) block:

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.Identity.Name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆