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

后端 未结 8 573
醉梦人生
醉梦人生 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:06

    With WebApi 5.0 this is slightly different. You can now do:

    controller.User = new ClaimsPrincipal(
      new GenericPrincipal(new GenericIdentity("user"), null));
    
    0 讨论(0)
  • 2020-12-29 19:07

    None of this ended up working for me, I used the solution on another question which uses Moq to set up a user name in the ControllerContext: https://stackoverflow.com/a/6752924/347455

    0 讨论(0)
  • 2020-12-29 19:07

    Here i found the solution for another way that how to set the user identity name for the controller level testing from the test method.

    public static void SetUserIdentityName(string userId)
            {
                IPrincipal principal = null;
                principal = new GenericPrincipal(new GenericIdentity(userId), 
                new string[0]);
                Thread.CurrentPrincipal = principal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = principal;
                }
            }
    
    0 讨论(0)
  • 2020-12-29 19:12

    When I run Unit test - in my case it uses Windows authentication and Identity.Name is my domain name, which I also want to change for the test. So I use such approach with 'hacking' things I want in IAuthenticationFilter

    0 讨论(0)
  • 2020-12-29 19:19

    The below one is only one way of doing this:

    public class FooController : ApiController {
    
        public string Get() {
    
            return User.Identity.Name;
        }
    }
    
    public class FooTest {
    
        [Fact]
        public void Foo() {
    
            var identity = new GenericIdentity("tugberk");
            Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
            var controller = new FooController();
    
            Assert.Equal(controller.Get(), identity.Name);
        }
    }
    
    0 讨论(0)
  • 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<ControllerContext>();
        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

    0 讨论(0)
提交回复
热议问题