asp.net - 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.
解决方案
有点晚了,但在
var userModel = await res.Content.ReadAsAsync<User>();
ReadAsAsync
需要是ReadAsStringAsync
推荐阅读
- python - 对于带有 pytest-cov 的 pytest:如何为覆盖版本 >= 5 指定 parallel=True
- flutter - 如何使底部导航栏在我的应用程序的每个页面上都可见?
- mysql - 如何将排序的数据插入另一个 sql 数据表?
- php - 从 wpdb 填充下拉列表
- delphi - 确定 DUnitX 中的测试顺序?
- java - 如果选择了特定项目,如何从微调器中获取选择项目并更改图像?
- javascript - 如何在具有“严格”和“非严格”模式的常规箭头 fn 中确定正确的“this”?
- javascript - 当信息不正确时用户提交时如何将内容保留在表单中,这样他们就不必输入所有内容
- robotframework - 在 Robot Framework 中运行 Netconf 不会返回正确的输出
- python - 用python解码/编码十六进制数字