单元测试Web Api 2模拟用户

时间:2014-06-11 05:54:35

标签: unit-testing asp.net-web-api mocking asp.net-web-api2

我试图在我的Api控制器测试中模拟User.Identity。

这是我的api方法:

    [Route(Urls.CustInfo.GetCustomerManagers)]
    public HttpResponseMessage GetCustomerManagers([FromUri]int groupId = -1)
    {
        var user = User.Identity.Name;
        if (IsStaff(user) && groupId == -1)
        {
            return ErrorMissingQueryStringParameter;
        }
        ...
    }

我按照这篇文章中的建议:Set User property for an ApiController in Unit Test来设置用户属性。

这是我的测试:

    [TestMethod]
    public void User_Without_Group_Level_Access_Call_GetCustomerManagers_Should_Fail()
    {
        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"}); 
        var response = m_controller.GetCustomerManagers();

        Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
    }

但是当运行测试时,User属性始终为null。

我甚至尝试在调用User.Identity之前移动用于将CurrentPrincipal设置为api方法的行,但它仍然为null。

我做错了什么?如果这种方法不适用于web api 2,那么模拟/模拟User属性的最佳方法是什么?

谢谢!

3 个答案:

答案 0 :(得分:15)

您可以在ControllerContext.RequestContext.Principal中设置用户:

controller.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"});

或简写等同物:

controller.User = new GenericPrincipal(new GenericIdentity("Bob", "Passport"), new[] {"managers"});

答案 1 :(得分:0)

我确实设法解决了这个问题,实际上为GetUserId()设置了一些东西,而不是在得票最多的答案中给出的用户名。请注意oyu必须从使用FakeItEasy转换为您选择的模拟工具。

$(document).ready(function() {
  $("#test-circle").circliful({
    animationStep: 5,
    foregroundBorderWidth: 15,
    backgroundBorderWidth: 15,
    percent: value,
    iconPosition: 'middle',
    textStyle: 'font-size:8px;',
    text: "This circle for demo",
  });
});

然而,一个更好的解决方案(如果我再次编写代码)将抽象调用GetUserId的实际代码,这样我就可以注入一个可以进行调用的对象,这很容易被模拟。有点像工厂。

答案 2 :(得分:0)

尽管这是一篇过时的文章,但我也想补充一下自己的想法。

如果您只想模拟用户身份,则无需使用任何模拟框架,因为您不能使用模拟框架(至少与moq无关)来模拟用户身份。

只需如下分配HttpContext.current属性

HttpContext.Current = new HttpContext(
    new HttpRequest("", "http://localhost", ""),
    new HttpResponse(null)
);

HttpContext.Current.User就是这样

HttpContext.Current.User = 
           new GenericPrincipal(
               new GenericIdentity("name"),
               new []{"manager","Admin"}
           );

现在HttpContext.Current.User.Identity.Name将在Web api控制器中可用。

如果要模拟其他属性或对象,请使用moq或任何其他框架。但是模拟HttpContext就像上面一样简单。

相关问题