相关疑难解决方法(0)

在单元测试中模拟HttpClient

我有一些问题试图包装我的代码用于单元测试.问题是这样的.我有接口IHttpHandler:

public interface IHttpHandler
{
    HttpClient client { get; }
}
Run Code Online (Sandbox Code Playgroud)

而使用它的类,HttpHandler:

public class HttpHandler : IHttpHandler
{
    public HttpClient client
    {
        get
        {
            return new HttpClient();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后是Connection类,它使用simpleIOC来注入客户端实现:

public class Connection
{
    private IHttpHandler _httpClient;

    public Connection(IHttpHandler httpClient)
    {
        _httpClient = httpClient;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个单元测试项目,有这个类:

private IHttpHandler _httpClient;

[TestMethod]
public void TestMockConnection()
{
    var client = new Connection(_httpClient);

    client.doSomething();  

    // Here I want to somehow create a mock instance of the http client
    // Instead of the …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing moq

90
推荐指数
15
解决办法
7万
查看次数

使用Moq模拟HttpClient

我喜欢对使用的类进行单元测试HttpClient.我们HttpClient在类构造函数中注入了对象.

public class ClassA : IClassA
{
    private readonly HttpClient _httpClient;

    public ClassA(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<HttpResponseMessage> SendRequest(SomeObject someObject)
    {
        //Do some stuff

        var request = new HttpRequestMessage(HttpMethod.Post, "http://some-domain.in");

        //Build the request

        var response = await _httpClient.SendAsync(request);

        return response;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我们喜欢对ClassA.SendRequest方法进行单元测试.我们正在使用Ms Test单元测试框架和Moq模拟.

当我们试图嘲笑它时HttpClient,它会抛出NotSupportedException.

[TestMethod]
public async Task SendRequestAsync_Test()
{
    var mockHttpClient = new Mock<HttpClient>();

    mockHttpClient.Setup(
        m => m.SendAsync(It.IsAny<HttpRequestMessage>()))
    .Returns(() => …
Run Code Online (Sandbox Code Playgroud)

c# unit-testing mstest moq dotnet-httpclient

7
推荐指数
4
解决办法
9051
查看次数

模拟 HttpClientFactory 使用 Moq 框架创建模拟 HttpClient

我有一个方法,其中包含HttpClientFactory创建一个HttpClient. 该方法调用SendAsync其中的方法。我需要操纵SendAsync方法来向我发送成功消息,无论它作为参数。

我想测试这个方法

public class TestService
{
    private readonly IHttpClientFactory _clientFactory;

    public TestService(IHttpClientFactory clientFactory)
    {
         _clientFactory = clientFactory;
    }

    public async Task<bool> TestMethod(string testdata)
    {
        var message = new HttpRequestMessage(); //SIMPLIFIED CODE
        var client = _clientFactory.CreateClient();
        var response = await client.SendAsync(message);

        if(response.IsSuccessStatusCode){
            return true;
        }else{
            return false;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试的是

private readonly Mock<IHttpClientFactory> _mockHttpClientFactory;
private readonly Mock<HttpClient> _mockHttpClient;

[Fact]
public void TestMethod_ValidHttpRequest_ReturnsTrue()
{
    var httpClient = _mockHttpClient
                        .Setup(x => x.SendAsync(It.IsAny<HttpRequestMessage>()))
                        .ReturnsAsync(new …
Run Code Online (Sandbox Code Playgroud)

c# moq xunit

5
推荐指数
1
解决办法
6016
查看次数

使用 moq 模拟 HttpMessageHandler - 如何获取请求的内容?

在决定我想为测试发回什么样的响应之前,有没有办法获取http请求的内容?多个测试将使用此类,每个测试将有多个 http 请求。此代码无法编译,因为 lambda 不是异步的,并且其中有一个等待。我是 async-await 的新手,所以我不确定如何解决这个问题。我曾短暂考虑过拥有多个 TestHttpClientFactories,但这意味着代码重复,因此如果可能,我决定反对它。任何帮助表示赞赏。

public class TestHttpClientFactory : IHttpClientFactory
{
    public HttpClient CreateClient(string name)
    {
        var messageHandlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

        messageHandlerMock.Protected()
            .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
            .ReturnsAsync((HttpRequestMessage request, CancellationToken token) =>
            {
                HttpResponseMessage response = new HttpResponseMessage();
                var requestMessageContent = await request.Content.ReadAsStringAsync();

                // decide what to put in the response after looking at the contents of the request

                return response;
            })
            .Verifiable();

        var httpClient = new HttpClient(messageHandlerMock.Object);
        return httpClient;
    }
}
Run Code Online (Sandbox Code Playgroud)

asp.net integration-testing moq async-await httpcontent

4
推荐指数
1
解决办法
1286
查看次数