Vet*_*van 5 c# asp.net unit-testing asp.net-web-api asp.net-identity
我正在使用Web API 2.在web api控制器中,我使用了GetUserId使用Asp.net Identity生成用户ID的方法.
我必须为该控制器编写MS单元测试.如何从测试项目中访问用户ID?
我在下面附上了示例代码.
Web API控制器
public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations)
{
int userId = RequestContext.Principal.Identity.GetUserId<int>();
bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations);
return Ok(isSavePlayerLocSaved );
}
Run Code Online (Sandbox Code Playgroud)
Web API控制器测试类
[TestMethod()]
public void SavePlayerLocTests()
{
var context = new Mock<HttpContextBase>();
var mockIdentity = new Mock<IIdentity>();
context.SetupGet(x => x.User.Identity).Returns(mockIdentity.Object);
mockIdentity.Setup(x => x.Name).Returns("admin");
var controller = new TestApiController();
var actionResult = controller.SavePlayerLoc(GetLocationList());
var response = actionResult as OkNegotiatedContentResult<IEnumerable<bool>>;
Assert.IsNotNull(response);
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用上面的模拟方法.但它没有用.当我从测试方法调用到控制器时,如何生成Asp.net用户身份?
如果请求已通过身份验证,则应使用相同的原则填充User属性
public IHttpActionResult SavePlayerLoc(IEnumerable<int> playerLocations) {
int userId = User.Identity.GetUserId<int>();
bool isSavePlayerLocSaved = sample.SavePlayerLoc(userId, playerLocations);
return Ok(isSavePlayerLocSaved );
}
Run Code Online (Sandbox Code Playgroud)
因为ApiController你可以User在安排单元测试时设置属性.然而,这种扩展方法正在寻找一个,ClaimsIdentity所以你应该提供一个
现在的测试看起来像
[TestMethod()]
public void SavePlayerLocTests() {
//Arrange
//Create test user
var username = "admin";
var userId = 2;
var identity = new GenericIdentity(username, "");
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId.ToString()));
identity.AddClaim(new Claim(ClaimTypes.Name, username));
var principal = new GenericPrincipal(identity, roles: new string[] { });
var user = new ClaimsPrincipal(principal);
// Set the User on the controller directly
var controller = new TestApiController() {
User = user
};
//Act
var actionResult = controller.SavePlayerLoc(GetLocationList());
var response = actionResult as OkNegotiatedContentResult<IEnumerable<bool>>;
//Assert
Assert.IsNotNull(response);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
647 次 |
| 最近记录: |