单元测试 - 如何将控制器用户设置为通用主体对象

Arj*_*una 2 c# tdd unit-testing asp.net-web-api asp.net-apicontroller

更新的完整解决方案:

我要测试的 WebApi 控制器方法:

using Microsoft.AspNet.Identity;
using System.Web.Http;


[Authorize]
public class GigsController : ApiController
{
    private readonly IUnitOfWork _unitOfWork;

    public GigsController(IUnitOfWork unitOfWork)
    {
        _unitOfWork = unitOfWork;
    }        

    [HttpDelete]
    public IHttpActionResult Cancel(int id)
    {
        var userId = User.Identity.GetUserId();
        var gig = _unitOfWork.Gigs.GetGigWithAttendees(id);

        if (gig.IsCanceled)
            return NotFound();

        if (gig.ArtistId != userId)
            return Unauthorized();

        gig.Cancel();

        _unitOfWork.Complete();

        return Ok();
    }
}
Run Code Online (Sandbox Code Playgroud)

单元测试类:

[TestClass]
public class GigsControllerTests
{
    private GigsController _controller;
    public GigsControllerTests()
    {
        var identity = new GenericIdentity("user1@domain.com");
        identity.AddClaim(
            new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "user1@domain.com"));
        identity.AddClaim(
            new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", "1"));

        var principal = new GenericPrincipal(identity, null);

        var mockUoW = new Mock<IUnitOfWork>();
        _controller = new GigsController(mockUoW.Object);
        _controller.User = principal;
    }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

无法将错误 CS0200 属性或索引器“ApiController.User”分配给它——它是只读的

https://i.stack.imgur.com/YDQJS.png

Fab*_*bio 7

您可以通过分配 ControllerContext

var user = new ClaimsPrincipal();
var context = new ControllerContext
{
    HttpContext = new DefaultHttpContext
    {
        User = user
    }
};

controllerUnderTest.ControllerContext = context;
Run Code Online (Sandbox Code Playgroud)