How to perform XUnit test on a jwt authorised web api?

Viewed 639

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.

1 Answers

a bit late but in

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

ReadAsAsync needs to be ReadAsStringAsync

Related