2016-10-04 61 views
0

我有一個OAuthServerProvider認證用戶名和密碼後發出令牌。當用戶名或密碼無效時,我拒絕owin上下文,默認情況下將返回400 Bad Request作爲狀態碼。NUnit測試用例跳過owin中間件

但我想用401 Unauthorized

迴應要做到這一點我寫了一箇中間件將檢查頭,看看自定義標題是存在,如果是將401

替換狀態碼
if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey(Constants.OwinChallengeFlag)) 
{ 
    var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag); 
    context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault()); 
    context.Response.Headers.Remove(Constants.OwinChallengeFlag); 
} 

這個工作絕對沒問題,當我用小提琴打它時,但是我在下面寫的單元測試總是得到400.不知何故,當我用我的單元測試請求中間件時,跳過了。

[TestFixture] 
public class UnitTest1 
{ 
    private TestServer _server; 

    [SetUp] 
    public void SetUp() 
    { 
     _server = TestServer.Create<Startup>(); 
    } 

    [Test] 
    public void ShouldReturnUnauthorizedResponse() 
    { 

     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/token"); 

     //wrong password 
     var requestContent = "grant_type=password&UserName=foo&Password=bar"; 

     request.Content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded"); 

     var response = _server.HttpClient.SendAsync(request).Result; 

     //This assert fails, but shouldn't 
     Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); 
    } 
} 

需要知道我在做什麼錯在這裏。

+0

1)這是一個集成測試而不是單元測試。 2)顯示啓動配置和完整的中間件。 3)你是否緩衝響應以便下載訪問它? – Nkosi

回答

0

我終於想通了....

await _next.Invoke(environment)是罪魁禍首。我用與傳入中間件的相同環境字典對象調用它,因此對單元測試沒有反映對對象context的修改。

下面的代碼按預期方式工作....

public async Task Invoke(IDictionary<string, object> environment) 
{ 
    var context = new OwinContext(environment); 

    var response = context.Response; 

    response.OnSendingHeaders(state => 
    { 
     var resp = (OwinResponse)state; 
     if (resp.StatusCode == 400 && resp.Headers.ContainsKey(Constants.OwinChallengeFlag)) 
     { 
      var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag); 
      resp.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault()); 
      resp.ReasonPhrase = HttpStatusCode.Unauthorized.ToString(); 
      resp.Headers.Remove(Constants.OwinChallengeFlag); 
     } 
    }, response); 

    await _next.Invoke(context.Environment); 
} 

除了使從改性context對象獲得的environment變量,修改響應標頭內的response.OnSendingHeaders是必不可少的,這保證了報頭之前被修改響應標題被分派。

但是我仍然不知道小提琴手是如何挑選正確的響應狀態碼的。

希望它可以幫助別人。