【发布时间】:2017-10-10 12:34:43
【问题描述】:
更新完整解决方案:
我要测试的 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();
}
}
单元测试类:
[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;
}
我收到以下错误:
错误 CS0200 属性或索引器“ApiController.User”不能 分配给 -- 它是只读的
【问题讨论】:
-
这是不正确的。
ApiController.User不是只读的。所以你需要提供一个minimal reproducible example 可以用来重现问题。这样我们就可以更好地评估问题的真正原因。 -
您好 Nkosi,我已经更新了完整的解决方案,它仍然显示 ApiController.User 是只读的
-
同时显示
GigsController声明。 -
刚刚更新的伙伴 :)
-
我使用提供的代码尝试重现您的问题,但正如预期的那样,代码编译,允许将值分配给
ApiController.User属性。除非您在示例中显示的内容有其他内容,否则您显示的错误将无法重现。
标签: c# unit-testing asp.net-web-api tdd asp.net-apicontroller