Writing Unit Test for methods that use User.Identity.Name in ASP.NET Web API

后端 未结 8 610
醉梦人生
醉梦人生 2020-12-29 18:33

I am writing test cases using the Unit Test for ASP.NET Web API.

Now I have an action which makes a call to some method I have defined in the service layer, where I

8条回答
  •  悲&欢浪女
    2020-12-29 19:21

    Here's another way I found in the NerdDinner testing tutorial. It worked in my case:

    DinnersController CreateDinnersControllerAs(string userName)
    {
    
        var mock = new Mock();
        mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
        mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
    
        var controller = CreateDinnersController();
        controller.ControllerContext = mock.Object;
    
        return controller;
    }
    
    [TestMethod]
    public void EditAction_Should_Return_EditView_When_ValidOwner()
    {
    
        // Arrange
        var controller = CreateDinnersControllerAs("SomeUser");
    
        // Act
        var result = controller.Edit(1) as ViewResult;
    
        // Assert
        Assert.IsInstanceOfType(result.ViewData.Model, typeof(DinnerFormViewModel));
    }
    

    Make sure you read the full section: Mocking the User.Identity.Name property

    It uses the Moq mocking framework that you can install in your Test project using NuGet: http://nuget.org/packages/moq

提交回复
热议问题