Moq cannot Setup
extension methods. If you know what the extension method accesses then some cases you can mock a safe path through the extension method.
WriteAsync(HttpResponse, String, CancellationToken)
Writes the given text to the response body. UTF-8 encoding will be used.
directly accesses the HttpResponse.Body.WriteAsync
where Body
is a Stream
via the following overload
/// <summary>
/// Writes the given text to the response body using the given encoding.
/// </summary>
/// <param name="response">The <see cref="HttpResponse"/>.</param>
/// <param name="text">The text to write to the response.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="cancellationToken">Notifies when request operations should be cancelled.</param>
/// <returns>A task that represents the completion of the write operation.</returns>
public static Task WriteAsync(this HttpResponse response, string text, Encoding encoding, CancellationToken cancellationToken = default(CancellationToken))
{
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
if (encoding == null)
{
throw new ArgumentNullException(nameof(encoding));
}
byte[] data = encoding.GetBytes(text);
return response.Body.WriteAsync(data, 0, data.Length, cancellationToken);
}
This means you would need mock response.Body.WriteAsync
//Arrange
var expected = "Hello World";
string actual = null;
var responseMock = new Mock<HttpResponse>();
responseMock
.Setup(_ => _.Body.WriteAsync(It.IsAny<byte[]>(),It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()))
.Callback((byte[] data, int offset, int length, CancellationToken token)=> {
if(length > 0)
actual = Encoding.UTF8.GetString(data);
})
.ReturnsAsync();
//...code removed for brevity
//...
Assert.AreEqual(expected, actual);
The callback was used to capture the arguments passed to the mocked member. Its value was stored in a variable to be asserted later in the test.