2016-04-04 212 views
1

我嘗試使用Azure移動應用程序.Net Server中的授權對我的api控制器進行單元測試。具有授權的單元測試Azure移動.NET控制器

我控制器的方法是這樣的:

[Authorize] 
public HttpResponseMessage SomeMethod() 
{ 
    var claimsPrincipal = this.User as ClaimsPrincipal; 
    string userId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value; 
    return Request.CreateResponse(HttpStatusCode.OK, userId); 
} 

我在單元測試方法類似這樣的配置我的要求:

[TestMethod] 
public void SomeMyAPIControllerTest(){ 
    var config = new HttpConfiguration(); 
    var request = new HttpRequestMessage(); 
    request.RequestUri = new Uri("http://localhost:50268/api/MyAPI"); 
    request.Headers.Add("x-zumo-auth", "_user_auth_token_"); 
    request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; 
    var controller = new MyAPIController(TestContext) 
    { 
     Request = request 
    }; 
    var response = controller.SomeMethod(); 
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 
} 

我控制器的方法通過在本地主機上招搖工作正常,但通過單元測試方法這是行不通的。 當我嘗試檢索經過身份驗證的用戶信息時,claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)返回null

我想在請求配置中有一個錯誤。有什麼建議麼?

回答

1

爲了測試您可以直接在ApiController上設置User

更新您的測試方法,爲控制器創建一個假用戶。

[TestMethod] 
public void SomeMyAPIControllerTest(){ 
    // Arrange 
    var config = new HttpConfiguration(); 
    var request = new HttpRequestMessage(); 
    request.RequestUri = new Uri("http://localhost:50268/api/MyAPI"); 
    request.Headers.Add("x-zumo-auth", "_user_auth_token_"); 
    request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config; 
    //Create test user 
    var username = "[email protected]"; 
    var identity = new GenericIdentity(username, ""); 
    //Add fake claim for test 
    var nameIdentifierClaim = new Claim(ClaimTypes.NameIdentifier, username); 
    identity.AddClaim(nameIdentifierClaim); 
    var principal = new GenericPrincipal(identity, roles: new string[] { }); 
    var user = new ClaimsPrincipal(principal); 
    // Set the User on the controller directly 
    var controller = new MyAPIController(TestContext) 
    { 
     Configuration = config, 
     Request = request, 
     User = user 
    }; 

    //Act 
    var response = controller.SomeMethod(); 

    //Assert 
    Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); 
} 
+0

謝謝@Nkosi。用你的例子,我可以得到「身份/聲明/名稱:[email protected]」,但是如何添加「身份/聲明/名稱標識符」類型? – deman4ik

+0

@ deman4ik我已經更新了答案,以包含您請求的信息。如果你覺得這個問題有幫助,可以隨意投票。如果這確實可以解決您的問題,請不要忘記標記爲已回答。謝謝 – Nkosi

+0

是的,這正是我想要的!謝謝! – deman4ik