[英]Unit Test using MS fakes: HttpClient and await
我有创建HttpClient实例并调用某些方法并以异步模式返回响应的类。
对于ReadAsAsync,我使用了nuget包“ System.Net.Http.Formatting”。
源代码:
public class MyClass
{
readonly HttpClient client = new HttpClient();
public MyClass()
{
string myUrl = ConfigurationManager.AppSettings["MyWebAPI"];
client.BaseAddress = new Uri(myUrl);
}
public async Task<List<YourClass>> GetYourClass()
{
var filters = "string";
HttpResponseMessage response = await client.GetAsync(filters).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var notes = await response.Content.ReadAsAsync<List<YourClass>>();
return notes;
}
return null;
}
}
public class YourClass
{
private string Address { get; set; }
public YourClass(string address)
{
Address = address;
}
}
单元测试:
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
using (ShimsContext.Create())
{
MyClass obj = new MyClass();
ShimHttpClient shimHttpClient = new ShimHttpClient();
ShimHttpClient.Constructor = (t) =>
{
shimHttpClient = new ShimHttpClient();
shimHttpClient.GetAsyncString = (a) =>
{
return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
};
};
var returnVal = obj.GetYourClass();
}
}
private System.Net.Http.HttpResponseMessage function1()
{
return new System.Net.Http.HttpResponseMessage();
}
}
我们无法更改源代码。 但需要通过虚拟调用测试对GetAsync和ReadAsAync调用进行单元测试。
声明您的测试要异步运行并等待源类的响应
[TestMethod]
public async Task TestMethod1()
{
using (ShimsContext.Create())
{
MyClass obj = new MyClass();
ShimHttpClient shimHttpClient = new ShimHttpClient();
ShimHttpClient.Constructor = (t) =>
{
shimHttpClient = new ShimHttpClient();
await shimHttpClient.GetAsyncString = (a) =>
{
return new System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>(function1);
};
};
var returnVal = await obj.GetYourClass();
Assert.IsNotNull(returnVal);
//make more assertations on the returnVal
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.