模拟HttpResponse WriteAsync

时间:2018-04-27 15:02:16

标签: c# unit-testing asp.net-core moq xunit

我试图通过模拟WriteAsync来调用HttpResponse,我无法弄清楚要使用的语法。

var responseMock = new Mock<HttpResponse>();
responseMock.Setup(x => x.WriteAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()));

ctx.Setup(x => x.Response).Returns(responseMock.Object);

测试炸弹出现以下错误:

  

System.NotSupportedException:扩展方法的设置无效:x   =&GT; x.WriteAsync(It.IsAny(),It.IsAny())

最终我想验证是否已将正确的字符串写入响应。

如何正确设置?

2 个答案:

答案 0 :(得分:5)

这是一个似乎可以在.NET Core 3.1中运行的解决方案,以确保完整性:

const string expectedResponseText = "I see your schwartz is as big as mine!";

DefaultHttpContext httpContext = new DefaultHttpContext();
httpContext.Response.Body = new MemoryStream();

// Whatever your test needs to do

httpContext.Response.Body.Position = 0;
using (StreamReader streamReader = new StreamReader(httpContext.Response.Body))
{
    string actualResponseText = await streamReader.ReadToEndAsync();
    Assert.Equal(expectedResponseText, actualResponseText);
}

答案 1 :(得分:3)

Moq无法Setup扩展方法。如果您知道扩展方法访问的内容,那么您可以通过扩展方法模拟安全路径。

WriteAsync(HttpResponse, String, CancellationToken)

  

将给定文本写入响应正文。将使用UTF-8编码。

通过以下重载直接访问HttpResponse.Body.WriteAsync BodyStream的{​​{1}}

/// <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);
}

这意味着您需要模拟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);

回调用于捕获传递给模拟成员的参数。它的值存储在一个变量中,以便稍后在测试中断言。