HttpClient默认标头不能与Microsoft.Owin.Testing.TestServer一起使用

时间:2017-04-20 17:40:48

标签: asp.net-web-api2 integration-testing owin katana

我正在使用Microsoft.Owin.Testing库集成测试内存中的API。我已经在OWIN JWT中间件中添加了我的身份验证需求,现在我正在尝试传递生成的令牌来测试需要授权的控制器的请求。我可以向您保证JWT中间件设置正确,因为它在正常使用时工作得很好。但是,我观察到TestServer.HttpClient对象的一些奇怪行为。当我在HttpClient上设置默认授权头以传递令牌时,我的测试永远不会通过,因为无法识别令牌。但是,当我使用TestServer.CreateRequest(...)时,测试会正确传递并识别令牌。我更喜欢使用HttpClient方法,因为它们使用PostAsJsonAsync等所提供的所有扩展方法使事情变得更加容易。我开始认为{{1}中有一个错误或者我完全错过了什么。

这是我的测试类(使用NUnit3):

TestServer.HttpClient

我的控制员:

public class DefinitionsControllerTests
{
    private TestServer _server;
    private string _accessToken;

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

        var credentials = new FormUrlEncodedContent(new[] {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", "john.doe@mail.com"),
            new KeyValuePair<string, string>("password", "testing123")
        });

        // get token from OWIN JWT middleware
        dynamic resultBody = JObject.Parse(
            _server.HttpClient.PostAsync("/oauth/token", credentials).Result.Content.ReadAsStringAsync().Result);

        _accessToken = (string)resultBody.access_token;

        // this does not appear to ever work
        _server.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accessToken);
    }

    [TearDown]
    public void TearDown()
    {
        _server.Dispose();
    }

    [Test]
    public void GetById_WithExistingId()
    {
        // 401 Unauthorized response everytime and test fails
        var response = _server.HttpClient.GetAsync($"/api/definitions/{expected.Id}").Result;
        var actual = response.Content.ReadAsAsync<Definition>().Result;

        // 200 Ok every time and test passes
        // - these variables aren't part of the test but rather to show alternate request creation method that works
        var response2 = _server.CreateRequest($"/api/definitions/{expected.Id}")
            .AddHeader("Authorization", "Bearer " + _accessToken)
            .GetAsync()
            .Result;
        var actual2 = response.Content.ReadAsAsync<Definition>().Result;

        response.StatusCode.ShouldBe(HttpStatusCode.OK);
        actual.ShouldNotBeNull();
    }

    //...other test methods
}

任何人都知道为什么只有CreateRequest()有效?这有点令人生气。

1 个答案:

答案 0 :(得分:5)

问题是HttpClient属性每次都返回一个新实例。如果您保存该实例并重新使用它,它将起作用。 https://github.com/aspnet/AspNetKatana/blob/b850cd8b4de61e65bbd7127ce02b5df7c4cb6db5/src/Microsoft.Owin.Testing/TestServer.cs#L48