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

后端 未结 8 645
醉梦人生
醉梦人生 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: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);
        }
    }
    

提交回复
热议问题