Integration Controller Decorated with [Login]

My application is an ASP.NET Core 1.0 web API.

As the title says: How to check a controller decorated with an attribute Authorize?

For example, using this controller and the test method:

  [TestMethod]
  public void GetSomeDataTest()
  {
     var controller = new MyController();
     Assert.AreEqual(controller.GetSomeData(), "Test");
  }

  [Authorize]
  public ActionResult GetSomeData()
  {
     return this.Content("Test");
  }

This is just a sample code to let you guys answer. In fact, I am calling Controllerthrough an object TestServer.

It already was, but the accepted answer no longer works. Any suggestions on how I could "fake" the authenticity of users?

thank

+4
source share
2 answers

[TestInitialize]
public void Initialize()
{
    var claims = new List<Claim>() 
    { 
        new Claim(ClaimTypes.Name, "UserName"),
        new Claim(ClaimTypes.Role, "Admin")
    };
    var identity = new ClaimsIdentity(claims, "TestAuth");
    var claimsPrincipal = new ClaimsPrincipal(identity);
    Thread.CurrentPrincipal = claimsPrincipal;
}

.Net Core

private MyController _ctrl;

[TestInitialize]
public void Initialize()
{
    var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
    {
         new Claim(ClaimTypes.Name, "UserName"),
         new Claim(ClaimTypes.Role, "Admin")
    }));

    _ctrl = new MyController();
    _ctrl.ControllerContext = new ControllerContext()
    {
        HttpContext = new DefaultHttpContext() { User = user }
    };
}

[TestMethod]
public void GetSomeDataTest()
{
    Assert.AreEqual(_ctrl.GetSomeData(), "Test");
}
+4

, , , , ASP.NET, → , HTTP- ( , ).

, , Authorize unit test /. .

-1

Source: https://habr.com/ru/post/1673891/


All Articles