HttpResponse模拟WriteAsync

我试图在模拟HttpResponse上模拟对WriteAsync的调用,但我不知道要使用的语法.

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 : Invalid setup on an extension method: x
=> x.WriteAsync(It.IsAny(), It.IsAny())

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

如何正确设置?

解决方法:

Moq无法设置扩展方法.如果您知道扩展方法访问的内容,则可以在某些情况下通过扩展方法模拟安全路径.

WriteAsync(HttpResponse, String, CancellationToken)

Writes the given text to the response body. UTF-8 encoding will be used.

通过以下重载直接访问HttpResponse.Body.WriteAsync,其中Body是Stream

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

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

回调用于捕获传递给模拟成员的参数.它的值存储在变量中,以便稍后在测试中声明.

上一篇:c# – xUnit和测试的多个数据记录


下一篇:解决IE报错:Locale 'chinese' is not well-formed,或RangeError: 区域设置“chinese”的格式不正确的问题