using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
namespace AMWD.Common.Test
{
///
/// Wrapps the including the setup.
///
public class HttpMessageHandlerMoq
{
///
/// Initializes a new instance of the class.
///
public HttpMessageHandlerMoq()
{
Response = new() { StatusCode = HttpStatusCode.OK };
Callbacks = new();
Mock = new();
Mock.Protected()
.Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny())
.Callback(async (req, _) =>
{
var callback = new HttpMessageRequestCallback
{
Headers = req.Headers,
Method = req.Method,
Properties = req.Properties,
RequestUri = req.RequestUri,
Version = req.Version
};
if (req.Content != null)
{
callback.ContentBytes = await req.Content.ReadAsByteArrayAsync();
callback.ContentString = await req.Content.ReadAsStringAsync();
}
Callbacks.Add(callback);
})
.ReturnsAsync(Response);
}
///
/// Gets the mocked .
///
public Mock Mock { get; }
///
/// Gets the placed request.
///
public List Callbacks { get; private set; }
///
/// Gets the HTTP response, that should be "sent".
///
public HttpResponseMessage Response { get; private set; }
///
/// Disposes and resets the and .
///
public void Reset()
{
Response.Dispose();
Response = new() { StatusCode = HttpStatusCode.OK };
Callbacks.Clear();
}
///
/// Verifies the number of calls to the HTTP request.
///
///
public void Verify(Times times)
=> Mock.Protected().Verify("SendAsync", times, ItExpr.IsAny(), ItExpr.IsAny());
///
/// Represents the placed HTTP request.
///
public class HttpMessageRequestCallback
{
///
/// Gets the contents of the HTTP message.
///
public byte[] ContentBytes { get; internal set; }
///
/// Gets the contents of the HTTP message.
///
public string ContentString { get; internal set; }
///
/// Gets the collection of HTTP request headers.
///
public HttpRequestHeaders Headers { get; internal set; }
///
/// Gets the HTTP method used by the HTTP request message.
///
public HttpMethod Method { get; internal set; }
///
/// Gets of properties for the HTTP request.
///
public IDictionary Properties { get; internal set; }
///
/// Gets the used for the HTTP request.
///
public Uri RequestUri { get; internal set; }
///
/// Gets the string representation.
///
public string RequestUrl => RequestUri?.ToString();
///
/// Gets the HTTP message version.
///
public Version Version { get; internal set; }
}
}
}