我具有要进行单元测试的功能。看来我的HttpClient有问题。每当我在TestExplorer中运行它时,我都会收到此错误消息“ System.Net.Http.HttpRequestException:发送请求时发生错误。System.Net.WebException:基础连接已关闭”。
如何正确模拟httpClient?
我的实现
public class WaktuSolatServiceApi : IWaktuSolatServiceApi
{
private const string URL =
"http://api.azanpro.com/times/today.json?zone=sgr01&format=12-hour";
IWaktuSolatServiceApi waktu;
HttpClient client;
Solat solat;
public WaktuSolatServiceApi(HttpClient client, Solat solat)
{
this.client = client;
this.solat = solat;
}
public async Task<Solat> GetAsyncSet()
{
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(URL).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsStringAsync();
solat = JsonConvert.DeserializeObject<Solat>(dataObjects.Result);
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
Console.ReadLine();
}
return solat;
}
}
UnitTest Xunit
[Fact]
public async Task ShouldReturnBetul()
{
var solat = new Mock<Solat>();
Mock<IWaktuSolatServiceApi> mocksetting = new
Mock<IWaktuSolatServiceApi>();
Solat expected = new Solat
{
zone = "test"
};
var client = new Mock<HttpClient>();
var test = new WaktuSolatServiceApi(new HttpClient(), new Solat());
var final = await test.GetAsyncSet().ConfigureAwait(false);
Assert.NotNull(final);
Assert.Same(expected, final);
}
}