首页 > 解决方案 > How to perform XUnit test on a jwt authorised web api?

问题描述

I have to perform xunit test on api controller with authorize attribute. The API is protected using JWT Bearer token authorization. So to perform unit test on API ,I tried below code:

  private async Task<string> GetToken(string username, string password)
    {
        var user = new User
        {
            UserName = username,
            Password = password
        };

        var res = await _client.PostAsJsonAsync("api/validate", user);


        if (!res.IsSuccessStatusCode) return null;

        var userModel = await res.Content.ReadAsAsync<User>();
        return userModel?.Token;
    }

and then tried to call this GetToken method in unit test.

string token = await GetToken("user1", "password");
_client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

but its giving error message System.ArgumentNullException : String reference not set to an instance of a String. (Parameter 's')

Is there any other way to implement xunit test on jwt authorised web api.

标签: asp.netunit-testingjwttokenxunit

解决方案


有点晚了,但在

var userModel = await res.Content.ReadAsAsync<User>();

ReadAsAsync需要是ReadAsStringAsync


推荐阅读